Home > Software engineering >  Adding custom legend after theme(legend.title=element_blank(), legend.position='none')
Adding custom legend after theme(legend.title=element_blank(), legend.position='none')

Time:01-19

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?

CodePudding user response:

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

  • Related