ggplot2的相同图上的离散且连续的图例

时间:2018-06-07 09:06:08

标签: r ggplot2 legend

我正在制作一个显示三种不同类型的情节。 其中一种类型具有连续的方差,因此使用连续色标显示。 其他两种类型都有自己的颜色。

我只能获得一个连续类型的图例,而不是两个离散类型。我尝试使用建议here,但收到了消息

  

警告:忽略未知的美学:填写

如何获得连续线和离散线的图例?

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" ) 

制作的情节看起来像这样。 我想要相同的情节,但有一个额外的图例,显示类型2的黑色和类型3的蓝色。因此,图例将是离散和连续的混合。 enter image description here

2 个答案:

答案 0 :(得分:2)

好的,所以一个全新的答案:

这里是:

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

这是一个令人烦恼的解决方法,但它可以完成工作

你基本上使用show.legend获取第一个图例,fill强制使用第二个图例(因此忽略警告,因为显然没有任何东西可以填充一行),然后{ {1}}允许您将颜色添加到图例

答案 1 :(得分:0)

不完全确定所需的输出是什么

例如:

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

 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

或者是完全不同的东西

相关问题