[英]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 值A和B 。
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
手動設置帶有顏色的圖例。 您將vline
的color
命名為黑色,您可以通過"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.