繁体   English   中英

如何将 legened 添加到 geom_vline?

[英]How to add legened to geom_vline?

我有一个 dataframe ( df_new ) 看起来像这样:

date<- c("2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04", "2020-01-05")
A <- c(23, 41, 32, 58, 26)
B <- c(10, 20, 30, 40, 50)
  
df_new <- data.frame(date, A, B)
df_new$date <- as.Date(df_new$date)

我将以下代码用于 plot 值AB

ggplot(data = df_new, aes(x = date)) + 
  geom_line(aes(y = A, colour = "Value A")) + 
  geom_line(aes(y = B, colour = "Value B"))+
  labs(title = 'A & B Distribution',
       x = '',
       y = 'Value Count',
       color = " ") +
  theme_bw() +
  scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
                labels = trans_format("log10", math_format(10^.x)))+
  geom_vline(xintercept = as.numeric(as.Date("2020-01-03")), linetype=4)+
  theme(text=element_text(size=13),panel.spacing.x=unit(0.6, "lines"),
        panel.spacing.y=unit(1, "lines"))

它根据需要给我 plot 在此处输入图像描述 除了我想在值 B 下添加一个geom_vline图例,我在其中手动绘制了一条黑线。

请任何指导?

您可以使用scale_color_manual手动设置带有颜色的图例。 您将vlinecolor命名为黑色,您可以通过"black"="black"将其指定为图例中的值。 这可以手动更改为您想要的任何内容。 您可以使用以下代码:

library(tidyverse)
library(scales)
ggplot(data = df_new, aes(x = date)) + 
  geom_line(aes(y = A, colour = "Value A")) + 
  geom_line(aes(y = B, colour = "Value B"))+
  labs(title = 'A & B Distribution',
       x = '',
       y = 'Value Count',
       color = " ") +
  theme_bw() +
  scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
                labels = trans_format("log10", math_format(10^.x)))+
  geom_vline(xintercept = as.numeric(as.Date("2020-01-03")), linetype=4, color = "black")+
  theme(text=element_text(size=13),panel.spacing.x=unit(0.6, "lines"),
        panel.spacing.y=unit(1, "lines")) +
  scale_color_manual(name = "Legend", values = c("Value A" = "red", "Value B" = "blue", "black" = "black"))

Output:

在此处输入图像描述

暂无
暂无

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

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