Search code examples
rggplot2aesthetics

Bars do not get the color tried to give to them in a barplot


How to make all the bars blue except from the year 2005 that is red. My code doesn't do it. Is there a way to do this without specifying the color for every year in the data frame?

df <- data.frame(
  Body_part = sample(c("Head", "Arm", "Leg", "Torso"), 1000, replace = TRUE),
  Year = as.factor(sample(2003:2021, 1000, replace = TRUE))
)

ggplot(df, aes(x = fct_rev(fct_infreq(Body_part)), fill = Year)) +
  geom_bar(position = "dodge", stat = "count") +
  scale_fill_manual(values = c("blue", "2005" = "red")) +
  theme_light() +
  labs(title = "",
       x = "",
       y = "Count") +
  coord_flip()

enter image description here


Solution

  • From ?scale_fill_manual:

      values: a set of aesthetic values to map data values to. The values
              will be matched in order (usually alphabetical) with the
              limits of the scale, or with ‘breaks’ if provided. If this is
              a named vector, then the values will be matched based on the
              names instead. Data values that don't match will be given
              ‘na.value’.
    

    Noteworth is the na.value reference.

    ggplot(df, aes(x = fct_rev(fct_infreq(Body_part)), fill = Year)) +
      geom_bar(position = "dodge", stat = "count") +
      scale_fill_manual(values = c("2005" = "red"), na.value = "blue") +
      theme_light() +
      labs(title = "",
           x = "",
           y = "Count") +
      coord_flip()
    

    enter image description here

    Note that neither your plot nor this will show years other than "2005" in the legend. An alternative that at least gives a hint about the others:

    transform(df, Year2 = ifelse(as.character(Year) == "2005", "2005", "Other")) |>
      ggplot(aes(x = fct_rev(fct_infreq(Body_part)),
                 group = Year, fill = Year2)) + ## notice the changes here
      geom_bar(position = "dodge", stat = "count") +
      scale_fill_manual(name = "Year", values = c("2005"="red", "Other"="blue")) +
      theme_light() +
      labs(title = "",
           x = "",
           y = "Count") +
      coord_flip()
    

    enter image description here