我试图按照变量的大小对ggplot条形图中的类别进行重新排序,首先是最大的类别,然后是越来越小的类别。我尝试过以某种方式玩订单,但似乎只能手动设置订单,这对大数据集没什么帮助。
例如: 我们说我有以下数据:
mydata <- read.table(header=TRUE, text="
shop fruit varieties km_away
shop1 apple 0 12
shop1 banana 0 12
shop1 pear 2 12
shop1 melon 1 12
shop1 orange 1 12
shop1 peach 3 12
shop1 apricot 6 12
shop1 lime 1 12
shop2 apple 1 1
shop2 banana 0 1
shop2 pear 2 1
shop2 melon 2 1
shop2 orange 5 1
shop2 peach 4 1
shop2 apricot 11 1
shop2 lime 0 1
shop3 apple 0 2
shop3 banana 1 2
shop3 pear 2 2
shop3 melon 1 2
shop3 orange 4 2
shop3 peach 1 2
shop3 apricot 11 2
shop3 lime 1 2
shop4 apple 0 5
shop4 banana 0 5
shop4 pear 3 5
shop4 melon 2 5
shop4 orange 6 5
shop4 peach 1 5
shop4 apricot 9 5
shop4 lime 0 5
")
我可以像这样有效地想象它:
library(ggplot2)
library(RColorBrewer)
p <- ggplot(data = mydata, aes(x=reorder(shop, km_away), y=varieties, fill=fruit))+
geom_bar(stat="identity") + coord_flip()+scale_fill_brewer(palette="Accent")
p
但是我怎么告诉ggplot首先绘制杏子,然后是橘子等?这将使在视觉上比较不同商店的不同类别变得更加容易。
答案 0 :(得分:2)
您可以先获取按您感兴趣的数量排序的类别向量:
fruit_levels <- names(sort(tapply(mydata$varieties, mydata$fruit, sum)))
然后,在致电ggplot
时,将fill
映射到具有相应级别的因子变量:
p <- ggplot(data = mydata,
aes(x=reorder(shop, km_away), y=varieties,
fill=factor(fruit, levels = fruit_levels)))+
geom_bar(stat="identity") + coord_flip()+
scale_fill_brewer(name = "fruit", palette="Accent")
p
输出:
更新。更直接的方法是重新排序原始数据框中的因子级别,并像原始代码一样调用ggplot
:
mydata$fruit <- reorder(mydata$fruit, mydata$varieties, sum)
p <- ggplot(data = mydata, aes(x=reorder(shop, km_away), y=varieties, fill=fruit))+
geom_bar(stat="identity") + coord_flip()+scale_fill_brewer(palette="Accent")
p
更新2。在旧版ggplot2
(版本2之前)上,尝试指定order
美学:
p <- ggplot(data = mydata, aes(x=reorder(shop, km_away),
y=varieties,
fill=fruit, order=fruit)) +
geom_bar(stat="identity") + coord_flip()+scale_fill_brewer(palette="Accent")
p
如果您想要反转排序,请在排序变量前添加一个负号:
reorder(mydata$fruit, -mydata$varieties, sum)