How to use if_else() to set color in ggplot()?

Hey everyone, I'm taking the Google Data Analytics course on Coursera, and I wanted to know how to incorporate an if_else statement into my code to change the colors of charts based on conditions. The example the course showed me was a little confusing because they showed me on line of code, but I would've liked for them to show me all the code they used to make the graph, and where that specific if_else condition would fit into the entire code. So could someone give me an idea of where this piece of code would fit into with any kind of graph? Thank you.

The visualization shown on Coursera lesson:

The specific code I didn't understand:

The ifelse goes in the aes(). Note that I need to add scale_fill_identity to get the fill to be the actual colour I want .

library(ggplot2)

df <- data.frame (x = 1:10,  y = runif(10))

ggplot(
  df, 
  aes(
    x = x, 
    y = y, 
    fill = ifelse(y < 0.5, "blue", "yellow")
    )
  )+ 
  geom_col() +
  scale_fill_identity()
1 Like

Thank you! Question: I usually use scale_fill_manual. Is scale_fill_identity any different from that?

Here's an alternative that doesn't require scale_color_identity() — it just depends on what you want:

library(ggplot2)

x <- 1:10

ggplot() +
  geom_segment(
    aes(0, x, xend = x), 
    col = ifelse(x < 5, 'blue', 'yellow'),
    linewidth = 5)

Created on 2024-05-26 with reprex v2.0.2

scale_color_identity() allows color names that appear inside an aes() call to be interpreted literally. (They're automatically interpreted literally when they're not inside an aes() call, as in this example.)

1 Like

Thank you! I did try the scale_fill_identity() function, but I noticed that it removed the legend. How would I bring the legend back?

Yes, scale_fill_identity() is different from scale_fill_manual().

If I have an aes() where I say fill = variable_name, and the variable has the value "blue" then scale_fill_identity will give you the colour blue/ Scale fill_manual will give you whatever you tell it to.
For example:

scale_fill_manual(values = c("blue" = "chocolate", "yellow" = "forestgreen"))

would render blue as chcoolate and yellow as green, but show the -names- of those colors in the legend as "blue" and "yellow". scales map a value to another value, scale_*_identity maps to the colour with the same name, because it doesn't need to be scaled, we already know what the colour are. Of course this only works if the names exists as a colour:

fill = ifelse(y < 0.5, "rosebud", "yellow")

would give an error:

Error in `geom_col()`:
! Problem while converting geom to grob.
ℹ Error occurred in the 1st layer.
Caused by error:
! Unknown colour name: rosebud

?scale_fill_identity

will tell you:

These scales will not produce a legend unless you also supply the breaks , labels , and type of guide you want.

1 Like