Home > Back-end >  coloring barplot using a continuous variable - factor not working
coloring barplot using a continuous variable - factor not working

Time:04-23

library(tidyverse)
library(poliscidata)

world_red <- world %>% group_by(dem_level4) %>% summarize(number_of_countries = n(), oil=sum(oil, na.rm = TRUE))

colors <- c("green", "blue", "orange", "red")
p1 <- ggplot(data = world_red)   
        aes(x = reorder(dem_level4, -oil) , y = oil, 
            fill = factor(number_of_countries) )  
        geom_col()   
        scale_fill_manual(values = colors) 

The variable "world" is part of the loaded package.

There is no error message in this code, but the legend appears as "factor(number_of_countries"), but, of course, it should only be "number_of_countries". How can I achieve this?

Just writing

fill = number_of_countries)   

without calling factor () results in the error message "Continuous value supplied to discrete scale"

CodePudding user response:

You can add a name argument into scale_fill_manual:

p1 <- ggplot(data = world_red)   
  aes(x = reorder(dem_level4, -oil) , y = oil, 
      fill = factor(number_of_countries) )  
  geom_col()   
  scale_fill_manual(name = "number_of_countries", values = colors)

Or you can add a labs line, then give a new name to fill. You can also update the x and y axis labels here too (which I did below).

library(tidyverse)

p1 <- ggplot(data = world_red)   
  aes(x = reorder(dem_level4, -oil) , y = oil, 
      fill = factor(number_of_countries) )  
  geom_col()   
  scale_fill_manual(values = colors)  
  labs(fill='number_of_countries',
       y = "Oil", 
       x = "dem_level4")

Output

enter image description here

  • Related