Search code examples
rggplot2colorsgeom-hline

How to pass hex codes to geom_hline in ggplot?


In the code below I create a ggplot, p1, using data from df1. I would like to add a horizontal line at the score value for each item in df2, and colour each line using the corresponing hexcode for each item, contained in column item_hexcode.

I thought it would be straightforward to pass the hex codes to ggplot to determine the colour of each line, but I can't seem to work out how to. Every approach I try either throws an error or appears to treat the hex codes as strings/levels of a factor.

Can anyone point out where I'm going wrong?

library(tidyverse)
# create example dataframes
set.seed(123)
df1 <- tibble(x = 1:5, y = (sample(200:300, 5, replace = TRUE)/100))
df2 <- tibble(item = c("a", "a", "b", "c", "b"), 
              score = c(2.58, 2.63, 2.45, 2.13, 2.29), 
              item_hexcode = c("#DA020E", "#DA020E", "#034694", "#7CFC00", "#034694"))

# initial plot
p1 <- ggplot(df1, aes(x, y)) + geom_line() + ylim(2, 3)
p1

# overlay horizontal lines on first plot, and colour lines according to hexcodes
p2 <- p1 + geom_hline(data = df2, aes(yintercept = score, 
             colour = item_hexcode), linetype = "dashed" ) + 
  scale_color_manual(values = df2$item_hexcode)

p2

example_plot

Thanks!


Solution

  • I think you are looking for the function called scale_color_identity:

    p2 <- p1 + geom_hline(data = df2, aes(yintercept = score, 
                                          colour = item_hexcode), 
                          linetype = "dashed" ) + 
      scale_color_identity()
    
    p2
    

    The result

    This function is used when the values taken by the variable that you set for an aesthetic parameter can be directly used (here the values are hexadecimal codes that can be directly interpreted by ggplot as colors).

    You would use scale_color_manual if you had levels in your variable (e.g. "low", "medium", "high"), and wanted to assign specific colors to them (and not the default ones, or colors from a palette).