Home > Enterprise >  How to set up different colors for each bar using ggplot2 package?
How to set up different colors for each bar using ggplot2 package?

Time:06-13

I am using 'mpg' data set and ggplot2 package to create a bar plot, and it is required that the colors of bars are defined by the 'class' variable such that the color for the value '2seater' is red, for the value 'pickup' is green, and all others are white. Here is my code:

    mpg %>% ggplot(aes(class), fill = x)   geom_bar(width = 0.7, color = "black", size = 0.8)  
  scale_fill_manual(values = c("2seater" = "red",
                               "compact" = "white",
                               "midsize" = "white",
                               "minivan" = "white",
                               "pickup" = "green",
                               "subcompact" = "white",
                               "suv" = "white"))

The problem is, when I execute this code, the colors of bars remain as default. Could anyone tell me what goes wrong with my code? Thank you very much

CodePudding user response:

As @user438383 advised in the comments, you need to specify the fill variable in the aes() call.

library(ggplot2)

mpg |> ggplot(aes(class, fill = class))  
  geom_bar(width = 0.7)  
  scale_fill_manual(values = c("2seater" = "red",
                               "compact" = "white",
                               "midsize" = "white",
                               "minivan" = "white",
                               "pickup" = "green",
                               "subcompact" = "white",
                               "suv" = "white"))  
  theme(legend.position = "none")

Created on 2022-06-12 by the enter image description here

CodePudding user response:

If you have many categories, you might want to specify the color for a handful of categories and a default color for the rest.

It's also handy to keep argument settings (such as color specs in this case) separate from the code to generate plots.

library("tidyverse")

special_colors <- list(
  "2seater" = "red",
  "pickup" = "green"
)
default_color <- "white"

mpg %>%
  ggplot(aes(class, fill = class))  
  geom_bar(width = 0.7)  
  scale_fill_manual(
    values = unlist(special_colors),
    na.value = default_color
  )  
  theme(legend.position = "none")

Created on 2022-06-12 by the reprex package (v2.0.1)

  • Related