Home > database >  How to fill colors of stacked bar plot depending on colors column of df in R using ggplot
How to fill colors of stacked bar plot depending on colors column of df in R using ggplot

Time:11-17

I am trying to create a stacked bar plot with the colors I am assigning in the "col" column of the df. I tried to do it using scale_color_identity().

The colors were assigned randomly using the following code, because I have a total of 300 countries and cannot assign colors manually.

color <- grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = T)]
colors <- fread("country_color.txt", header = TRUE, fill = TRUE)
colors[,col := sample(color, nrow(colors))]

Where the file country_color.txt only has the names of all the countries of my df.

My df looks like this after doing a left_join with the new color values (colors) and the rest of my data (producer_countries).

Country    year   total_value  col    
USA      1995   100        green
China    1995   120        red
Other    1995   150        brown
USA      2000   188        green
China    2000   177        red
Other    2000   320        brown

This is the code for the plot, but it is somehow not using the colors assigned in the df.

ggplot(producer_countries, aes(fill=reorder(Country, total_value), y=total_value, x=year))       
  geom_bar(position="stack", stat="identity",  color = "black", aes(colour=col)) 
  scale_color_identity()  
  xlab("Year")  
  ylab("Quantity)

Thanks!

CodePudding user response:

You should use aes(fill=col) in the geom_bar() call, and then use scale_fill_identity() as follows:

ggplot(producer_countries, aes(fill=reorder(Country, total_value), y=total_value, x=year))       
  geom_bar(position="stack", stat="identity",  color = "black", aes(fill=col)) 
  scale_fill_identity()  
  xlab("Year")  
  ylab("Quantity")
  • Related