r - 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 的蓝色。因此,图例将是离散和连续的混合。
解决方案
好的,所以一个全新的答案:
这里是:
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
让您将颜色添加到图例
推荐阅读
- typeorm - 无法运行 TypeORM 测试
- javascript - 如何使用 JS 自动填充 Google 表单
- objective-c - Objective-C 反射 - 获取 NSArray 的泛型类型
- python - 如何用beautifulsoup提取网页某个部分的所有链接?
- tkinter - 将 rgba 与 tkinter 一起使用
- html - 导入的图像未在 React 中显示
- python - 如何在不使用 timedelta 的情况下转到时间序列中的下一个日期
- entity-framework - 获取查询数据查看
- java - XSD 到 JAXB 文件和 JAXB 到具有数据库关系的 JPA 实体类
- excel - 将公式从 MS Access 数据库导入 MS Excel