在R中订购条形图 [英] Order barchart in R

查看:100
本文介绍了在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通过FreqName进行排序:

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

这篇关于在R中订购条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆