1

I have the following data:

set.seed(100)
vals <- rnorm(100)
groups <- c(rep('group a', 30), rep('group b', 70))
df <- data.frame('vals'=vals, 'groups'=groups)

I plot the distributions of vals within groups like this:

ggplot(df, aes(y=vals, x=groups, fill=groups)) +
geom_boxplot() +
theme_minimal() +
scale_fill_brewer(palette = "Set3") +
geom_hline(yintercept=0.5, color='red', lty='dashed', size=1) +
geom_hline(yintercept=-0.5, color='blue', lty='dashed', size=1) +
theme(legend.title=element_blank(), legend.position='none') 

This produces the following picture.

enter image description here

I would like to include a legend for the blue and red horizontal lines but not for the boxplots. How do I do that?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Otto Kässi
  • 2,943
  • 1
  • 10
  • 27
  • I found this https://stackoverflow.com/questions/40914194/ggplot2-completely-custom-legend, but sadly the solution was too convoluted for me to follow. Is there a more elegant way for doing this? – Otto Kässi Jan 16 '23 at 14:43

1 Answers1

3

You could use the aes of linetype for each geom_hline with scale_linetype_manual and say that the boxplot should not be shown like this:

set.seed(100)
vals <- rnorm(100)
groups <- c(rep('group a', 30), rep('group b', 70))
df <- data.frame('vals'=vals, 'groups'=groups)

library(ggplot2)
ggplot(df, aes(y=vals, x=groups, fill=groups)) +
  geom_boxplot(show.legend = FALSE) +
  theme_minimal() +
  scale_fill_brewer(palette = "Set3") +
  geom_hline(aes(yintercept=0.5, lty='red'), color='red', size=1) +
  geom_hline(aes(yintercept=-0.5, lty='blue'), color='blue', size=1) +
  scale_linetype_manual(name = "Legend", values = c(2, 2), 
                        guide = guide_legend(override.aes = list(color = c("red", "blue")))) 

Created on 2023-01-16 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53