Home > Software design >  get legend for two different data sets in ggplot
get legend for two different data sets in ggplot

Time:01-31

I am trying to create a legend from two different data sets. An example as below

ggplot(data = mtcars,aes(x = mpg, y = wt)) 
  geom_point(aes(colour = drat)) 
  geom_line(aes(colour = drat)) 
  geom_point(data = iris, aes(x = Sepal.Width, y = Petal.Length)) 
  geom_line(data = iris, aes(x = Sepal.Width, y = Petal.Length),linetype = "dashed") 
  scale_color_gradientn(colours=c('red','yellow','green'))

In the first data (mtcars) the color is according to a certain column value (drat). But in the second data (iris) it is just x and y points. How can I get line as the two lines as legend in addition to the color legend which is already present.

CodePudding user response:

Easiest way is to pass names to linetype within the aes() calls. The names become the legend labels. You can then use scale_linetype_manual to set linetypes there:

library(ggplot2)

ggplot(data = mtcars,aes(x = mpg, y = wt)) 
  geom_point(aes(colour = drat)) 
  geom_line(aes(colour = drat, linetype = "Cars")) 
  geom_point(data = iris, aes(x = Sepal.Width, y = Petal.Length)) 
  geom_line(data = iris, aes(x = Sepal.Width, y = Petal.Length,
                             linetype = "Iris")) 
  scale_color_gradientn(colours=c('red','yellow','green'))  
  scale_linetype_manual(values = c(
    "Cars" = "solid",
    "Iris" = "dotted"
  ))

  • Related