[英]ggplot Adding manual legend to plot without modifying the dataset
我試圖在不修改數據集的情況下向 plot 添加手動圖例,因為數據集和標記均值、中位數等的線是不同的概念。
存在解決修改數據問題的方法,例如Adding manual legend to a ggplot
這是一個簡化的例子,真實的數據集更復雜:
vec <-c(rep(1,100),rep(2,100),rep(3,80),rep(4,70),rep(5,60))
tbl <- as_tibble(vec)
mean_vec <- mean(vec)
cols <- c("Frequency"="grey",
"mean"="blue")
ggplot(as_tibble(tbl)) +
aes(x = value) +
geom_histogram(binwidth=1) +
geom_vline(xintercept=mean_vec,col="blue",size=1)+
theme_minimal() +
scale_color_manual(values=cols)+
scale_fill_manual(name="Test",values=cols)
為什么 plot 中缺少圖例?
如果你想有一個傳奇,那么你必須在美學上map。 否則scale_color/fill_manual
將無效:
vec <- c(rep(1, 100), rep(2, 100), rep(3, 80), rep(4, 70), rep(5, 60))
tbl <- data.frame(value = vec)
mean_vec <- mean(vec)
cols <- c(
"Frequency" = "grey",
"mean" = "blue"
)
library(ggplot2)
ggplot(tbl) +
aes(x = value) +
geom_histogram(aes(fill = "Frequency"), binwidth = 1) +
geom_vline(aes(color = "mean", xintercept = mean_vec), size = 1) +
theme_minimal() +
scale_color_manual(values = "blue") +
scale_fill_manual(name = "Test", values = "grey")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.