The easiest way to reorder bars manually

I wonder if there is an easier way to do the manual reordering of bars that I did with the code below, that includes creating new data frame. I'd like to do that without creating another data frame. Is there a way?

A plot with bars in wrong order

ggplot(data1, aes(x=question, y=mean)) +
  geom_bar(stat ="identity")+
  geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd)) +
  coord_flip()

The trick with new data frame

data2 <- data1 
data2$question <- factor(data2$question,
                         levels = c("Q4", "Q3", "Q2", "Q1"))

A plot with bars in right order

ggplot(data2, aes(x=question, y=mean)) +
  geom_bar(stat ="identity")+
  geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd)) +
  coord_flip()

data1

data1 <- structure(list(question = c("Q1", "Q2", "Q3", "Q4"), n = c(10L, 
10L, 10L, 10L), mean = c(4.9, 5.1, 4.9, 4.1), sd = c(0.994428926011753, 
1.66332999331662, 1.28668393770792, 1.28668393770792)), row.names = c(NA, 
4L), class = c("tbl_df", "tbl", "data.frame"))

You could just change the levels of question in place in data1, or if you do not want to do that, you can change the levels using pipes and avoid saving the change at all. Here is a version of the latter.

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.5
library(dplyr)
data1 <- structure(list(question = c("Q1", "Q2", "Q3", "Q4"), 
                        n = c(10L,10L, 10L, 10L), 
                        mean = c(4.9, 5.1, 4.9, 4.1), 
                        sd = c(0.994428926011753, 1.66332999331662, 1.28668393770792, 1.28668393770792)), 
                   row.names = c(NA, 4L), class = c("tbl_df", "tbl", "data.frame"))
data1 %>% mutate(question = factor(.$question, levels = c("Q4", "Q3", "Q2", "Q1"))) %>% 
  ggplot(aes(x=question, y=mean)) +
  geom_bar(stat ="identity")+
  geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd)) +
  coord_flip()

Created on 2021-09-06 by the reprex package (v0.3.0)

1 Like

This is a very good way to do it. Thank you very much

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.