Reputation: 419
I would like to create a simple horizontal barplot with dodged bars, but I am struggeling with the ordering of the (horizontal) bars. When I do a normal barplot (stacked or dodged) I can easily control the order of the bars by setting useful factor levels and ordering the data frame according to the corresponding variable. However, ordering the data frame does not seem to have any effect on the order of the bars in the horizontal plot. I found some similar questions, but I am not sure whether they correspond to my problem (the plots look a bit different).
df1 <- data.frame (year = as.factor(c(rep(2015,3),rep(2016,3),rep(2017,3))),
value = c(50,30,20,60,70,40,20,50,80),
set = rep(c("A","B","C"),3) )
ggplot() + geom_bar(data= df1, aes(y=value, x=set, fill=year),
stat="identity", position="dodge" ) +
coord_flip()
What I want is a horizontal plot that shows the 2015-bar on top and the 2017-bar on the bottom. Interestingly, the bars are ordered that way when I leave out coord_flip(), but I need the plot to be horizontal. Ordering the data this way does not change the plot:
df1 <- df1[rev(order(df1$year)),]
I am grateful for any hint :)
Upvotes: 1
Views: 2325
Reputation: 801
You've hit on one of ggplot2's idiosyncrasies - the ordering of bars after coord_flip
gets a little unintuitive. To change it, you have to reverse the order of your factor levels in df1$year
, not just the values themselves. See below:
library(ggplot2)
df1 <- data.frame (year = as.factor(c(rep(2015,3),rep(2016,3),rep(2017,3))),
value = c(50,30,20,60,70,40,20,50,80),
set = rep(c("A","B","C"),3) )
levels(df1$year)
#> [1] "2015" "2016" "2017"
df1$year <- factor(df1$year, levels = rev(levels(df1$year)))
ggplot(df1) +
geom_bar(aes(y=value, x=set, fill=year),
stat="identity", position="dodge" ) +
coord_flip()
If you want to keep your legend in the original order, you can access this with guide_legend
.
ggplot(df1) +
geom_bar(aes(y=value, x=set, fill=year),
stat="identity", position="dodge" ) +
guides(fill = guide_legend(reverse = TRUE)) +
coord_flip()
Upvotes: 6