0

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. 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?

Histogram with mean line. The legend is missing in the plot

scs
  • 567
  • 6
  • 22

1 Answers1

2

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

stefan
  • 90,330
  • 6
  • 25
  • 51