Order columns in plot

Advertisements

I’d like to make a stocked graph with geom_col() with below dataset.

tmp.df <- data.frame(
  original = c(2.68, 1.05, 72.89, 11.81, 11.67, 2.85, 1.11, 72.74, 12.05, 11.95),
  sensitivity = c('Si', 'Si', 'Si', 'Si', 'Si', 'STi', 'STi', 'STi', 'STi', 'STi'),
  parameters = c('OMd', 'ED6_N', 'CP', 'dr_N', 'GE', 'OMd', 'ED6_N', 'CP', 'dr_N', 'GE')
)

Thus I did like below:

ord.eng <- c("CP", "GE", "OMd", "ED6_N", "dr_N")

library(ggplot2)
ggplot(tmp.df, aes(x = sensitivity, y = original))+
    geom_col(aes(fill = parameters), width = 0.5, color = "black")+
    ggtitle("Nu/Total N excretion") +
    xlab("Sobol index")+
    ylab("Sobol indices (%)")+
    theme_classic()+
    theme(plot.title = element_text(face = "bold", hjust = 0.5, size = 18),
          axis.text.x = element_text(color = "black", size = 18),
          axis.text.y = element_text(color = "black", size = 18),
          axis.title = element_text(face = "bold", size = 18, color = "black"),
          legend.text = element_text(size = 15),
          legend.title = element_text(hjust = 0.5, size = 15))+
    scale_y_continuous(breaks = seq(0, 140, 20))+
        scale_fill_manual(name = "Variables", limits = ord.eng,
                      values = c("CP" = "White", "GE" = "ivory", "OMd" = "ivory3", "ED6_N" = "gray", "dr_N" = "black"))

However, the bar chart didn’t stock ‘ord.eng’ order.
It changed just legend order.
But I’d like to stock it same order with legend.

Do you have any good ideas?

Thank you for your help.

Result bar plot

>Solution :

One way of doing this is to turn the column you want to order by into a factor. The levels argument tells R the different values the variable can have, and ggplot uses the order of levels when deciding how to stack:

tmp.df %>%
    mutate(parameters = factor(parameters, levels = ord.eng)) %>% ### changed line ###
    ggplot(aes(x = sensitivity, y = original, fill = parameters)) +
    geom_col(aes(fill = parameters), width = 0.5, color = "black")+
    ggtitle(sprintf("Nu/Total N excretion"))+
    xlab("Sobol index")+
    ylab("Sobol indices (%)")+
    theme_classic()+
    theme(plot.title = element_text(face = "bold", hjust = 0.5, size = 18),
          axis.text.x = element_text(color = "black", size = 18),
          axis.text.y = element_text(color = "black", size = 18),
          axis.title = element_text(face = "bold", size = 18, color = "black"),
          legend.text = element_text(size = 15),
          legend.title = element_text(hjust = 0.5, size = 15))+
    scale_y_continuous(breaks = seq(0, 140, 20))+
        scale_fill_manual(name = "Variables", limits = ord.eng,
                      values = c("CP" = "White", "GE" = "ivory", "OMd" = "ivory3", "ED6_N" = "gray", "dr_N" = "black"))

Leave a ReplyCancel reply