我有一个图表,显示了操作系统的移动使用情况。我想添加垂直线以标识这些操作系统的发布时间。我将仔细检查图表,然后再检查代码。
图表 -
编码 -
dev %>%
group_by(os) %>%
mutate(monthly_change = prop - lag(prop)) %>%
ggplot(aes(month, monthly_change, color = os)) +
geom_line() +
geom_vline(xintercept = as.numeric(ymd("2013-10-01"))) +
geom_text(label = "KitKat", x = as.numeric(ymd("2013-10-01")) + 80, y = -.5)
我不想创建图例中的文本,而是创建一个图例来标识每条线。我想给他们每个人自己的颜色,然后有一个图例来标识每个人。像这样-
我可以这样制作自己的自定义图例吗?
您当然可以创建自己的自定义图例,但这有点复杂,因此我将逐步介绍一些虚假数据。
伪数据包含来自正态分布的100个样本(monthly_change
针对您的数据),5个分组(类似于os
数据中的变量)以及从随机起点开始的日期序列。
library(tidyverse)
library(lubridate)
y <- rnorm(100)
df <- tibble(y) %>%
mutate(os = factor(rep_len(1:5, 100)),
date = seq(from = ymd('2013-01-01'), by = 1, length.out = 100))
您已经使用colour
aes拨打电话了geom_line
,因此您需要选择其他aes才能映射到的呼叫geom_vline
。在这里,我使用linetype
和调用来scale_linetype_manual
根据需要手动编辑线型图例。
ggplot(df, aes(x = date, y = y, colour = os)) +
geom_line() +
# set `xintercept` to your date and `linetype` to the name of the os which starts
# at that date in your `aes` call; set colour outside of the `aes`
geom_vline(aes(xintercept = min(date),
linetype = 'os 1'), colour = 'red') +
geom_vline(aes(xintercept = median(date),
linetype = 'os 2'), colour = 'blue') +
# in the call to `scale_linetype_manual`, `name` will be the legend title;
# set `values` to 1 for each os to force a solid vertical line;
# use `guide_legend` and `override.aes` to change the colour of the lines in the
# legend to match the colours in the calls to `geom_vline`
scale_linetype_manual(name = 'lines',
values = c('os 1' = 1,
'os 2' = 1),
guide = guide_legend(override.aes = list(colour = c('red',
'blue'))))
然后,您可以得到一个不错的自定义图例。下次请记住,如果您可以提供数据,或者提供一个可重复的示例,那么我们可以更好地回答您的问题,而不必生成伪造的数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句