Home > Enterprise >  ggplot2 add background colour to legend title
ggplot2 add background colour to legend title

Time:11-03

I want to change the background colour of only the legend title (not the entire legend).

If I start with the below code:

library(ggplot2)
#produce a ggplot
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, colour=Species))   
  geom_point()

I can use theme( legend.title = element_rect( fill = "lightblue", size = 0.5, linetype = "solid", colour = "black")) to change the background of the entire legend which isnt what I am after.

Is there anyway to just change the background colour of the legend title ?

CodePudding user response:

Yes, using the ggtext package, one can do

library(ggplot2)
library(ggtext)

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, colour=Species))   
  geom_point()  
  theme(legend.title = element_textbox(fill = 'red', color = 'white'))

enter image description here

  • Related