更改堆积条形图的绘图顺序

时间:2016-11-09 00:07:18

标签: r ggplot2

我正在尝试更改堆积条形图中组的绘图顺序。其他人也问了类似问题,例herehere但我似乎无法获得类似的工作。

这是一个玩具示例。我有一个数据框,其中包含许多站点,它们的纬度以及每个站点上的老鼠,老鼠,兔子和狗的数量。我想制作一个堆积条形图,其中的网站按y轴的纬度排序,x轴上的动物数量。我希望动物条按特定顺序绘制(例如按大小,从最小到最大)。

我编写的代码我觉得应该可以使用,但是我为动物规定绘图顺序的努力只会重新排列传奇,而​​不是情节本身。

library(ggplot2)
df <- read.table(header=TRUE, text="site    group   taxa    latitude
A   mouse   2   -20
                               B    rat 3   -17
                               C    dog 6   -18
                               D    rabbit  7   -24
                               A    rabbit  2   -20
                               B    mouse   5   -17
                               C    rabbit  3   -18
                               D    dog 2   -24
                               A    dog 3   -20
                               B    rabbit  4   -17
                               C    mouse   3   -18
                               D    mouse   2   -24")

plotOrder <- c("mouse","rat","rabbit","dog") #set the order in which I want to plot the groups
df$group <- factor(as.character(df$group), levels = plotOrder) #reorders the legend & colour, not plotting order

plot1 <- 
  ggplot(data = df, 
         aes(x=reorder(site, latitude), y=taxa, fill=group))+
  geom_bar(aes(order = group), stat="identity") + 
  coord_flip()
plot1

提前致谢。

1 个答案:

答案 0 :(得分:2)

您可以通过订购整个data.frame

来实现这一目标
plot1 <- 
  ggplot(data = df[order(df$site, df$group),], 
         aes(x=reorder(site, latitude), y=taxa, fill=group))+
  geom_bar(stat="identity") + 
  coord_flip()
plot1

enter image description here

相关问题