简体   繁体   中英

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 .

Approaches to solve the problem modifying the data exist, eg 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?

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

If you want to have a legend then you have to map on aesthetics. Otherwise scale_color/fill_manual will have no effect:

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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