Search code examples
rcolorbar

use colorFactor to change color of barplot


pal_leaf= colorFactor(palette = c("red","orange", "yellow", "green", "darkgreen"), 
                          levels = c(0.9, 0.7, 0.5, 0.3, 0.1))
    
barplot(communities$acc_100k, col =pal_leaf(communities$acc_100k_coef), names.arg=communities$GEN, las=2, cex.names = 0.8)

How can i do this in ggplot. I could not find any questions except using scale_fill_gradient. But i did not like the aesthetics of the result, because you could barely distinguish between the colors. So does anyone know a better solution, where i get the exact same result as in my code?

This is the result i want to get: enter image description here


Solution

  • We don't have your data, so it's difficult to see what's going on without a reproducible example. However, suppose we have

    communities <- data.frame(acc_100k = c(1280, 1180, 1110, 1080, 1075, 1070,
                                           1030, 1000, 950, 930, 880, 820, 820,
                                           800, 790, 780),
                              GEN = c('Hannover', 'Köln', 'Bremen', 'Dresden',
                                      'Nürnberg', 'Düsseldorf', 'Hamburg',
                                      'Berlin', 'München', 'Frankfurt am Main',
                                      'Leipzig', 'Duisburg', 'Dortmund',
                                      'Stuttgart', 'Essen', 'Mannheim'),
                              acc_100k_coef = c(0.9, 0.9, 0.7, 0.7, 0.7, 0.7,
                                                0.5, 0.5, 0.5, 0.5, 0.3, 0.3,
                                                0.3, 0.1, 0.1, 0.1))
    

    Running your base R barplot code with this data set gives the following plot:

    barplot(communities$acc_100k, 
            col = pal_leaf(communities$acc_100k_coef), 
            names.arg = communities$GEN, las = 2, cex.names = 0.8)
    

    enter image description here

    The ggplot equivalent would be something like:

    ggplot(communities, 
           aes(factor(GEN, GEN), acc_100k, fill = pal_leaf(acc_100k_coef))) +
      geom_col(linewidth = 0.4, color = 'black') +
      labs(x = NULL) +
      scale_fill_identity() +
      theme(line = element_line(linewidth = 0.5),
            axis.line.x = element_blank(),
            axis.ticks.x = element_blank(),
            axis.text.x = element_text(angle = 90, hjust = 1))
    

    enter image description here