ggplot 在不修改数据集的情况下添加手动图例进行绘图

ggplot Adding manual legend to plot without modifying the dataset

我试图在不修改数据集的情况下向绘图添加手动图例,因为数据集和标记均值、中位数等不同的概念

存在解决修改数据问题的方法,例如

这里是一个简化的例子,真实的数据集更复杂:

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) 

为什么剧情中少了传说?

要想有传奇,就要在美学上作图。否则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")