Home > Mobile >  ggplot Adding manual legend to plot without modifying the dataset
ggplot Adding manual legend to plot without modifying the dataset

Time:04-18

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, e.g. Histogram with mean line. The legend is missing in the plot

CodePudding user response:

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

  • Related