0
votes

I am making a plot which shows three different types. One of the types has a continuous number of variances so it is shown using a continuous colour scale. The other two types have their own colours.

I can only get a legend to show for the continuous type, not the two discrete types. I tried using the advice here, but got the message

Warning: Ignoring unknown aesthetics: fill

How can I get a legend for both the continuous and discrete lines?

library(tidyverse)
library(ggplot2)

type1 <- tibble(y = rep(1:10, each = 20 ), x =  rep(1:20, times = 10), type = rep(1:10, each = 20 ) %>% as.character)

type2 <- tibble(y = seq(from = 0.5, to = 10, by=0.5), x = 1:20, type = "A")
type3 <- tibble(y = seq(from = 10, to = 0.5, by=-0.5), x = 1:20, type = "B")

 type1 %>% #need to remove infinte values 
    ggplot(aes(x, y, group = type)) + 
   geom_line(aes(colour = y)) +  
   scale_colour_gradientn(colors = c("red",   "limegreen"), name = "Type1 value") +
   geom_line(data = type2, 
             aes(x,y)) +
   geom_line(data = type3, 
             aes(x, y), colour = "blue" ) 

The plot produced looks like this. I want the same plot but with an additional legend that shows a black for type 2 and blue for type 3. Thus the legend would be a mix of discrete and continuous. enter image description here

2

2 Answers

2
votes

OK, so a whole new answer:

here it is:

type1 %>% #need to remove infinte values 
  ggplot(aes(x, y, group = type)) + 
  geom_line(aes(colour = y), show.legend = TRUE) +  
  scale_colour_gradientn(colors = c("red",   "limegreen"), name = "Type1 value") +
  geom_line(data = type2, 
        aes(x,y, fill = 'type2'), color = 'black') +
  geom_line(data = type3, 
        aes(x, y, fill = 'type3'), color = 'blue') +
  scale_fill_manual("Types", values=c(1, 1),
        guide=guide_legend(override.aes = list(colour=c("black", "blue")))
  )

enter image description here

It's a bit of an annoying workaround, but it does the job

You basically use show.legend to get the first legend, and the fill to force the second legend (so ignore the warning, because obviously there is nothing to fill in a line), and then guide_legend lets you add the colors to the legend

0
votes

Not exactly sure what is the desired output is

for example like this:

type1 %>% #need to remove infinte values 
  ggplot(aes(x, y, group = type)) + 
  geom_line(aes(color = 'type1')) +
  geom_line(data = type2, aes(x,y, color='type2'))  +
  geom_line(data = type3, aes(x, y, color='type3'))  

enter image description here

or

 type1 %>% #need to remove infinte values 
  ggplot(aes(x, y, group = type)) + 
  geom_line(aes(color = type), show.legend = TRUE) +
  geom_line(data = type2, aes(x,y, color='type2'), show.legend = TRUE)  +
  geom_line(data = type3, aes(x, y, color='type3'), show.legend = TRUE) 

enter image description here

or is it something entirely different