繁体   English   中英

ggplot2:手动添加图例到现有图例

[英]ggplot2: add legend manually to existing legend

对于以下 plot 我想有 2 个选项来添加图例:

  • 添加一个显示单条虚线(黑色)的图例,其中包含文本“3 天移动平均线”。 条形图的图例应保留
  • 添加一个图例,显示 3 条虚线(颜色与条形图例相同),文本为“3 天移动平均线”。 条形图的图例应保留

有人知道怎么做吗?

示例代码:

dat <- data.frame( x = c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6),
                   y = c(sample(10:30,6),sample(60:80,6),sample(120:150,6)),
                   z = c("A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C"))


dat2 <- dat %>%
  group_by(z) %>%
  mutate(roll_mean = rollmean(y,2, align = "right", fill=NA))


ggplot(data=dat2, aes(x=x, y=y, fill=z)) +
  geom_bar(stat="identity", position=position_dodge2(preserve = "single")) +
  geom_line(aes(y=roll_mean, color=z),size=1.1, linetype = "dashed") +
  theme_classic()                   

这是您的第二个要点的解决方案:

ggplot(data=dat2, aes(x=x, y=y, fill=z)) +
  geom_bar(stat="identity", position=position_dodge2(preserve = "single")) +
  geom_line(aes(y=roll_mean, color=z),size=1.1, linetype = 2) +
  theme_classic() +
  scale_colour_manual(name="3 day moving average",
                      values=c("A" = "#F8766D", "B" = "#00BA38", "C" = "#619CFF"), 
                      guide = guide_legend(override.aes=aes(fill=NA))) +
  theme(legend.key.size =  unit(0.5, "in"))

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM