Shery Shery - 3 months ago 22
R Question

Order bar graph by value ggplot2

My df:

summary2

Source: local data frame [4 x 2]

mean Patch
(dbl) (fctr)
1 3.210293 Scotland
2 3.555884 UK
3 3.883458 UK North
4 4.003116 Department


The df is already ordered by mean but when I draw bar plot, it messes up the order.

Here is the code:

ggplot(summary2,aes(x=Patch,y=mean, fill = Patch)) +
geom_bar(colour="black",stat = "identity")


Any ideas how to put it in ordered bar graph?

Answer

A solution that's completely inspired by this post:

df = read.table(header = TRUE, 
text = 'mean      Patch
1 3.210293   Scotland
2 3.555884         UK
3 3.883458   UKNorth
4 4.003116 Department')

ggplot(df,aes(x=Patch,y=mean, fill = Patch)) +
  geom_bar(colour="black",stat = "identity") + 
  scale_x_discrete(limits = df$Patch[order(df$mean)])

There are also other solutions mentioned via reordering.

Comments