在R中订购条形图
问题描述:
我正在尝试在R中绘制以下数据集:
I'm trying to plot the following data set in R:
fruit<-matrix(c("Apple","186","Banana","93","Elderberry","48","Durian", "28","Cherry", "28"),ncol=2,byrow=TRUE)
colnames(fruit) <- c("Name","Freq")
fruit <- data.table(fruit)
fruit$Freq <- as.numeric(as.character(fruit$Freq))
qplot(fruit$Name, fruit$Freq, geom="bar", stat="identity") + coord_flip()
但是它是按字母顺序绘制的
But it's being plotted in alphabetical order
我希望条形图显示从最高频率值到最低频率的水果.因此,苹果位于Y轴的顶部,然后是香蕉,等等...:
I want the barplot to show the fruit from highest frequency value to lowest. So Apple at the top of the Y axis, then Banana, etc...:
Apple 186
Banana 93
Elderberry 48
Durian 28
Cherry 28
我尝试过各种因素和水平,但无法弄清楚.
I've tried to play with factors and levels but can't figure it out.
答
使用reorder
通过Freq
对Name
进行排序:
ggplot(fruit, aes(reorder(Name, Freq), Freq)) +
geom_bar(fill=hcl(195,100,65), stat="identity") + coord_flip() +
xlab("Fruit") + ylab("Frequency")
如果要Name
的任意顺序,则可以使用factor
手动进行:
If you want an arbitrary ordering of Name
, you can do it manually using factor
:
fruit$Name = factor(fruit$Name,
levels=c("Banana", "Durian", "Elderberry", "Apple", "Cherry"))
# Now ggplot will plot the bars in the order listed in the factor command
ggplot(fruit, aes(Name, Freq)) + geom_bar(stat="identity") + coord_flip()
最后一件事:您可以使用更少的代码来创建数据框架.例如:
One last thing: You can create your data frame with less code. For example:
fruit = data.frame(Name=c("Apple","Banana", "Elderberry", "Durian", "Cherry"),
Freq=c(186, 93, 48, 28, 28))