How to change the order of the ggplot2 bar graph?

Asked

Viewed 37 times

0

I’m trying to change the order of the bars so that they appear in the same order as in fill (from top to bottom: a, b, c).

df3<-data.frame(Locus =rep(c("gene1","gene2"), 3),
            variable = c("a", "a", "b", "b", "c", "c"),
           value = c(-2.855996957,
           -2.859492255,
           -1.362416086,
           -5.36910352,
           1.493580871,
           -2.509611265))


ggplot(df3, aes(x = Locus, y = value, fill = variable, 
                order = as.numeric(variable))) +
  geom_col(position = "dodge") +
  scale_fill_manual(values=c("yellow", "red", "blue"))+
  labs(title = NULL,
       x = NULL,
       y = "",
       fill = "Tratamentos")+
  coord_flip()+
  theme_classic()

Fig. wrong: Fig errada

Fig. desired: Fig correta

1 answer

0


Utilize position = position_dodge2(reverse = TRUE) within the function geom_col. The argument reverse = TRUE will reverse the bar order.

library(tidyverse)

df3 <-data.frame(Locus =rep(c("gene1","gene2"), 3),
                                variable = c("a", "a", "b", "b", "c", "c"),
                                value = c(-2.855996957,
                                                    -2.859492255,
                                                    -1.362416086,
                                                    -5.36910352,
                                                    1.493580871,
                                                    -2.509611265))


ggplot(df3, aes(x = Locus, y = value, fill = variable)) +
    geom_col(position = position_dodge2(reverse = TRUE, padding = 0)) +
    scale_fill_manual(values=c("yellow", "red", "blue"))+
    labs(title = NULL,
             x = NULL,
             y = "",
             fill = "Tratamentos")+
    coord_flip()+
    theme_classic()

Created on 2021-08-14 by the reprex package (v2.0.1)

By default, the function position_dodge2 creates the bars with a spacing between them. So I put the argument padding = 0 so that the bars are glued to each other, as in the example provided.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.