更改堆积条形图的绘图顺序 [英] Changing plotting order for stacked bar chart

查看:1530
本文介绍了更改堆积条形图的绘图顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图改变堆积条形图中组的绘图顺序。其他人也问过类似的问题,


I am trying to change the plotting order of groups in a stacked bar chart. Others have asked similar questions e.g. here and here but I can't seem to get anything similar to work.

Here is a toy example. I have a data frame with a number of sites, their latitude, and the number of mice, rats, rabbits and dogs at each of them. I would like to make a stacked bar chart with sites ordered by latitude on the y axis, and the number of animals on the x axis. I would like the animal bars plotted in a specific order (e.g. by size, smallest to largest).

I have written code that I think should work, but my effort to stipulate the plotting order for the animals only rearranges the legend, not the plot itself.

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

Thanks in advance.

解决方案

You can achieve this by ordering the whole 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

这篇关于更改堆积条形图的绘图顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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