我正在尝试在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()
但它是按字母顺序绘制的
我希望条形图显示从最高频率值到最低频率的水果。所以Apple位于Y轴的顶部,然后是Banana等......:
Apple 186
Banana 93
Elderberry 48
Durian 28
Cherry 28
我试图玩各种因素和水平,但无法弄清楚。
答案 0 :(得分:1)
使用reorder
按Name
订购Freq
:
ggplot(fruit, aes(reorder(Name, Freq), Freq)) +
geom_bar(fill=hcl(195,100,65), stat="identity") + coord_flip() +
xlab("Fruit") + ylab("Frequency")
如果您想要Name
的任意排序,可以使用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()
最后一件事:您可以使用更少的代码创建数据框。例如:
fruit = data.frame(Name=c("Apple","Banana", "Elderberry", "Durian", "Cherry"),
Freq=c(186, 93, 48, 28, 28))
答案 1 :(得分:1)
除了@Richard Scriven之外,您还可以使用以下base
代码进一步操纵条形图:
fruit <- fruit[order(Freq),]
par(mar = c(4,5,2,2))
barplot(fruit$Freq, xlim = c(0,200), xaxt = "n", space = 1, horiz = TRUE,
names.arg = fruit$Name, las = 2)
axis(1, at = seq(0,200,20))
mtext("Frequency (#)", 1, line = 2.5)