0

I have a bar plot with mean and sd plotted for each sample. I want to order the bar plots based on condition but they are being plotted on the x axis in alphabetical order of the sample names. This is the code I used to get the plot. Any help is appreciated.

ggplot(df, aes(x = Samples,y=Mean, fill = Condition, order=Condition)) + geom_bar(position=position_dodge(), stat="identity",
           colour='black') +
  geom_errorbar(aes(ymin=Mean-sd, ymax=Mean+sd),  position = position_dodge(width = 0.9))+
  coord_flip()

My data frame is here:

Data Frame

Bar Plot

stefan
  • 90,330
  • 6
  • 25
  • 51
mike ropri
  • 27
  • 6
  • It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. Please do not post an image of code/data/errors [for these reasons](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557). Just include the code, console output, or data (e.g., dput(head(x)) or data.frame(...)) directly. – stefan Sep 13 '22 at 15:43
  • 1
    As a simple fix you could try `df <- df %>% arrange(Condition) |> mutate(Samples = forcats::fct_inorder(Samples))` to rearrange your data by condition then use `fct_inorder` to set the order of your samples. – stefan Sep 13 '22 at 15:46
  • Will include a fake dataset. Also, my data frame is already ordered by condition that is why I am confused why ggplot is ordering it by alphabetical order of sample name when plotting? – mike ropri Sep 13 '22 at 15:58
  • 2
    Okay. Then you do not need the orange`. But by default ggplot2 orders alphabetically, i.e. the order in the data has no effect. Using `mutate(Samples = forcats::fct_inorder(Samples))` will fix that by converting to a factor and setting (!!) the order as in the data. – stefan Sep 13 '22 at 16:04

0 Answers0