首页 > 解决方案 > ggplot2 在同一图上的离散和连续图例

问题描述

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

我只能得到一个图例来显示连续类型,而不是两种离散类型。我尝试使用这里的建议,但得到了消息

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

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

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 的蓝色。因此,图例将是离散和连续的混合。 在此处输入图像描述

标签: rggplot2legend

解决方案


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

这里是:

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

在此处输入图像描述

这是一个有点烦人的解决方法,但它确实有效

您基本上用于show.legend获取第一个图例,并fill强制使用第二个图例(所以忽略警告,因为显然没有什么可以填写的行),然后guide_legend让您将颜色添加到图例


推荐阅读