R中具有给定频率的条形图

Bar chart in R with given frequencies

我需要在 R 中为以下数据制作条形图:174 个蓝色 m&ms、224 个红色、230 个黄色、215 个橙色、195 个绿色和 216 个棕色 m&ms 都在一个袋子里。我被要求做的是: "Make a bar chart of the observed relative frequency of colors in the bag." 但我不确定如何准确地做到这一点。 谢谢

使用 barplot()

data <- c(rep("blue",174),rep("red",224),rep("yellow",230),rep("orange",215),rep("green",195),rep("brown",216))
t <- table(data)
barplot(t/sum(t), col=names(t))

或者,最好使用 ggplot2

library(ggplot2)
data <- c(rep("blue",174),rep("red",224),rep("yellow",230),rep("orange",215),rep("green",195),rep("brown",216))
df <- data.frame(mnm=data)
ggplot(df, aes(x=mnm)) + geom_histogram(aes(y=(..count..)/sum(..count..),fill=mnm)) + scale_fill_manual(name="M&M", values=sort(as.character(unique(df$mnm)))) + ylab("Relative Frequency")