Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

r - Changing plotting order for stacked bar chart

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...