rggplot2geomgeom-hline

geom_hline ignoring colour aes for some reason


    line_data <- data.frame(value = c(1,2), color = as.factor(c("blue", "green"))
      plot1 <- plot1 +
        geom_hline(aes(yintercept = value, colour = color), line_data, linetype = "dashed", size = 0.5)

The above is a snippet of my code. No matter what I assign to color column, it will be ignored. I can assign integers or continuous numbers. it will be ignored.

EDITED:

The reason is because plot1 already has a scale_color_manual added to it. Now the challenge becomes how to make it work without having to remove the scale_color_manual?


Solution

  • Please post reproducible code to help us answer your question. We don't know what plot1 is.

    Use scale_colour_identity to tell ggplot2 to interpret the variable directly as a color:

    line_data <- data.frame(value = c(1,2), color = as.factor(c("blue", "green")))
    ggplot(line_data) +
      geom_hline(aes(yintercept = value, colour = color), line_data, linetype = "dashed", size = 0.5) +
      scale_colour_identity()
    

    enter image description here

    EDIT: To make a new color legend compatible with an existing one, re-specify scale_colour_manual. You will still get the warning Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale., but it works:

    library(ggplot2)
    
    # example plot1 with manual scale
    plot1data = data.frame(x=c(1,2,3,4),
                           y=c(1,2,3,4),
                           color=factor(c(1,1,1,2)))
    plot1 = ggplot(plot1data, aes(x=x, y=y, colour=color)) +
      geom_point() +
      scale_colour_manual(values=c('1'='green','2'='red'))
    
    # data you want to add to the plot
    line_data <- data.frame(value = c(1,2), color = as.factor(c("blue", "green")))
    
    # assume you have the plot1 object but no access to the code that generated it
    # extract colors from plot1
    ggdata = ggplot_build(plot1)$data[[1]]
    plot1_colours = ggdata$colour
    names(plot1_colours) = ggdata$group
    
    # use the values originally specified for plot1 (plot_colours); add additional custom values  
    plot1 + 
      geom_hline(aes(yintercept = value, colour = color), data = line_data, linetype = "dashed", size = 0.5) +
      scale_colour_manual(values=c(plot1_colours, 'blue'='blue', 'green'='green'))
    

    enter image description here Specify breaks if you want to remove some values from the legend:

    plot1 + 
      geom_hline(aes(yintercept = value, colour = color), data = line_data, linetype = "dashed", size = 0.5) +
      scale_colour_manual(values=c(plot1_colours, 'blue'='blue', 'green'='green'), breaks = names(plot1_colours))
    

    enter image description here