Frequency density barplot of categorical variable

耗尽温柔 提交于 2019-12-25 06:47:55

问题


I'd like to plot a barplot of frequency density of the following ordered categorical data:

summary(ACC[EA$TYPE=="A"])
NG SG LG MG HG 
 2 25 36 17  0 

If I plot:

plot(ACC[EA$TYPE=="A"])

I get:

But I'd like to divide all the values by the total to get a frequency density: Ie. plot(ACC[EA$TYPE=="A"]/sum(as.numeric(ACC[EA$TYPE=="A"]))) but that doesn't work. Any tips?

Cheers,


回答1:


The default plotting function for a factor is barplot. So if you want a different graph, it may be easier to directly use this function: (with a random factor example)

f <- factor(sample(letters[1:5], 100, r=T))
h <- table(f) / length(f)
barplot(h)

Getting the same result with ggplot2 is trickier, and for some reason, I needed to put the data in a data.frame for it to work:

dat <- data.frame(f = f)
library(ggplot2)
ggplot(dat, aes(x=f, y=..count.. / sum(..count..), fill=f)) + geom_bar()




回答2:


It would be easier to fix it with a reproducible example, so I created one for you. The following works like a charm:

# 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")

I see no reason why this could not work as long as ACC[EA$TYPE=="A"] is a numeric:

barplot(ACC[EA$TYPE=="A"]/sum(ACC[EA$TYPE=="A"]), ylab="Frequency")


来源:https://stackoverflow.com/questions/36495155/frequency-density-barplot-of-categorical-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!