我正在使用ggplot创建一个绘图,该绘图使用彩色点,垂直线,和水平线来显示数据。理想情况下,我想为geom_vline
和geom_hline
图层使用两种不同的颜色或线型比例,但ggplot不鼓励/禁止映射到相同美学的多个变量。
# Create example data
library(tidyverse)
library(lubridate)
set.seed(1234)
example.df <- data_frame(dt = seq(ymd("2016-01-01"), ymd("2016-12-31"), by="1 day"),
value = rnorm(366),
grp = sample(LETTERS[1:3], 366, replace=TRUE))
date.lines <- data_frame(dt = ymd(c("2016-04-01", "2016-10-31")),
dt.label = c("April Fools'", "Halloween"))
value.lines <- data_frame(value = c(-1, 1),
value.label = c("Threshold 1", "Threshold 2"))
如果我为两个geom_*line
设置线型美学,它们就会被放入。{
线型传奇在一起,这不一定具有逻辑意义
ggplot(example.df, aes(x=dt, y=value, colour=grp)) +
geom_hline(data=value.lines, aes(yintercept=value, linetype=value.label)) +
geom_vline(data=date.lines, aes(xintercept=as.numeric(dt), linetype=dt.label)) +
geom_point(size=1) +
scale_x_date() +
theme_minimal()
或者,我可以将其中一条线设置为使用颜色美学, 但随后又将传奇线条置于一个不合逻辑的传奇中 分组
ggplot(example.df, aes(x=dt, y=value, colour=grp)) +
geom_hline(data=value.lines, aes(yintercept=value, colour=value.label)) +
geom_vline(data=date.lines, aes(xintercept=as.numeric(dt), linetype=dt.label)) +
geom_point(size=1) +
scale_x_date() +
theme_minimal()
我发现的唯一部分解决方案是使用填充美学
geom_point
中的颜色和设置shape=21
使用可填写的形状,
但这会迫使点周围出现黑色边框。我可以摆脱
边框通过手动设置color="white
,然后是白色边框
掩盖点。如果我设置colour=NA
,则不会绘制任何点。
ggplot(example.df, aes(x=dt, y=value, fill=grp)) +
geom_hline(data=value.lines, aes(yintercept=value, colour=value.label)) +
geom_vline(data=date.lines, aes(xintercept=as.numeric(dt), linetype=dt.label)) +
geom_point(shape=21, size=2, colour="white") +
scale_x_date() +
theme_minimal()
这可能是ggplot的“你不能映射两个变量的情况”
同样的审美“规则可以/应该被打破,但我无法弄清楚它周围的方式。使用geom_point
填充显示最大的承诺,但没有办法删除点边界。
在这里绘制两种不同颜色或线型美学的想法?