Home > OS >  How to select legend items but still preserve the scale specified by scale_color_manual()
How to select legend items but still preserve the scale specified by scale_color_manual()

Time:05-22

Problem:

I am creating a 2D plot in ggplot. This plot has multiple curves depending on ordered factors. I would like a legend that includes only the first and last factors, and at the same time specify the colors to use for each factor.


What I have tried:

Let colors be a vector that contains the color specification for each factor. When using scale_color_manual(values=colors), ggplot tries to list in the legend ALL items.

To select only the first and last factors to show in the legend, I went with the recommendation of several answers on StackOverflow: use the breaks argument to specify factor value. This worked, but now only the curves relating to the first and last factors had the right colors, the others were grey (ie. NA color value).

Any attempt at including two separate scale_color_manual failed as well.

CodePudding user response:

You're on the right track. Just set breaks= to define the levels you want in the legend and values= to define the factor-color relationships.

data(iris)

library(ggplot2)

colors <- c("setosa" = "orange", "versicolor" = "red", "virginica" = "purple")
  
ggplot(data = iris)   
  geom_line(aes(x = Petal.Width, y = Petal.Length, color = Species))  
  scale_color_manual(breaks = c("setosa", "virginica"), values = colors)

enter image description here

  • Related