0

I have to reorder the bars of the plot with increasing value of y(nbi). Thanks in advance!

#NBI*Sig_lip
p4 <-ggplot(DF, aes(x=sig_lip, y=nbi, fill=sig_lip)) + 
  stat_summary(fun.y="mean", geom="bar",show.legend = TRUE) +  
  stat_summary(func="sd", geom="errorbar") + 
  theme_minimal()
p4+ coord_flip()
p4 + ggtitle(label = "nbi associated to signaling lipids")

plot

dc37
  • 15,840
  • 4
  • 15
  • 32
  • 2
    Does this answer your question? [Reorder bars in geom\_bar ggplot2](https://stackoverflow.com/questions/25664007/reorder-bars-in-geom-bar-ggplot2) – dc37 Apr 21 '20 at 17:41
  • Actually, my bad I'm not sure the solution proposed in this post will work for your example. See my answer below. – dc37 Apr 21 '20 at 17:48

1 Answers1

1

Here your issue to reorder bargraph is that you are calculating the mean and the standard deviation in ggplot2. So, if you pass the "classic" reorder(x, -y), it will set the order based on the individual values of y not the mean.

So, you need to calculate Mean and SD before passing nbi as an argument in ggplot2:

library(dplyr)
library(ggplot2)

DF %>% group_by(sig_lip) %>%
  summarise(Mean = mean(nbi, na.rm = TRUE),
            SD = sd(nbi, na.rm = TRUE)) %>%
  ggplot(aes(x = reorder(sig_lip,-Mean), y = Mean, fill = sig_lip))+
  geom_col()+
  geom_errorbar(aes(ymin = Mean-SD, ymax = Mean+SD))

Does it answer your question ?

If not, please provide a reproducible example of your dataset by follwoign this guide: How to make a great R reproducible example

dc37
  • 15,840
  • 4
  • 15
  • 32
  • 1
    Thanks! I just had to add: coord_flip(xlim = NULL, ylim = NULL, expand = TRUE, clip = "on" to flip the coordinates correctly! – erika lazzarin Apr 22 '20 at 07:01