简体   繁体   English

ggplot 在不修改数据集的情况下将手动图例添加到 plot

[英]ggplot Adding manual legend to plot without modifying the dataset

I am trying to add a manual legend to a plot without modifying the dataset , because the dataset and lines that mark mean , median etc. are different concepts .我试图在不修改数据集的情况下向 plot 添加手动图例,因为数据集和标记均值、中位数等的线是不同的概念

Approaches to solve the problem modifying the data exist, eg Adding manual legend to a ggplot存在解决修改数据问题的方法,例如Adding manual legend to a ggplot

Here is a simplified example, the real dataset is more complex:这是一个简化的例子,真实的数据集更复杂:

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) 

Why is the legend missing in the plot?为什么 plot 中缺少图例?

带平均线的直方图。情节中缺少图例

If you want to have a legend then you have to map on aesthetics.如果你想有一个传奇,那么你必须在美学上map。 Otherwise scale_color/fill_manual will have no effect:否则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.

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