分类变量的频率密度条形图
Frequency density barplot of categorical variable
我想绘制以下有序分类数据的频率密度条形图:
summary(ACC[EA$TYPE=="A"])
NG SG LG MG HG
2 25 36 17 0
如果我绘制:
plot(ACC[EA$TYPE=="A"])
我得到:
但我想将所有值除以总数以获得频率密度:
IE。
plot(ACC[EA$TYPE=="A"]/sum(as.numeric(ACC[EA$TYPE=="A"])))
但这不起作用。有什么建议吗?
干杯,
用 reproducible example 修复它会更容易,所以我为你创建了一个。以下作品很有魅力:
# creates the vector
x <- c(2, 25, 36, 17, 0)
names(x) <- c("NG", "SG", "LG", "MG", "HG")
# raw x = counts
barplot(x, ylab="Count")
# when divided by the total count, we obtain frequencies and we barplot them
barplot(x/sum(x), ylab="Frequency")
只要 ACC[EA$TYPE=="A"]
是数字,我看不出为什么这不起作用:
barplot(ACC[EA$TYPE=="A"]/sum(ACC[EA$TYPE=="A"]), ylab="Frequency")
factor
的默认绘图函数是 barplot
。所以如果你想要一个不同的图,直接使用这个函数可能会更容易:(以随机因子为例)
f <- factor(sample(letters[1:5], 100, r=T))
h <- table(f) / length(f)
barplot(h)
获取 same result with ggplot2
比较棘手,出于某种原因,我需要将数据放入 data.frame
中才能正常工作:
dat <- data.frame(f = f)
library(ggplot2)
ggplot(dat, aes(x=f, y=..count.. / sum(..count..), fill=f)) + geom_bar()
我想绘制以下有序分类数据的频率密度条形图:
summary(ACC[EA$TYPE=="A"])
NG SG LG MG HG
2 25 36 17 0
如果我绘制:
plot(ACC[EA$TYPE=="A"])
我得到:
但我想将所有值除以总数以获得频率密度:
IE。
plot(ACC[EA$TYPE=="A"]/sum(as.numeric(ACC[EA$TYPE=="A"])))
但这不起作用。有什么建议吗?
干杯,
用 reproducible example 修复它会更容易,所以我为你创建了一个。以下作品很有魅力:
# creates the vector
x <- c(2, 25, 36, 17, 0)
names(x) <- c("NG", "SG", "LG", "MG", "HG")
# raw x = counts
barplot(x, ylab="Count")
# when divided by the total count, we obtain frequencies and we barplot them
barplot(x/sum(x), ylab="Frequency")
只要 ACC[EA$TYPE=="A"]
是数字,我看不出为什么这不起作用:
barplot(ACC[EA$TYPE=="A"]/sum(ACC[EA$TYPE=="A"]), ylab="Frequency")
factor
的默认绘图函数是 barplot
。所以如果你想要一个不同的图,直接使用这个函数可能会更容易:(以随机因子为例)
f <- factor(sample(letters[1:5], 100, r=T))
h <- table(f) / length(f)
barplot(h)
获取 same result with ggplot2
比较棘手,出于某种原因,我需要将数据放入 data.frame
中才能正常工作:
dat <- data.frame(f = f)
library(ggplot2)
ggplot(dat, aes(x=f, y=..count.. / sum(..count..), fill=f)) + geom_bar()