Search code examples
rggplot2customizationlegend

Can I customize individuals items in a ggplot legend?


Is it possible to make guides with different fonts, regarding a factor? I'm trying to plot my multivariate data and, in addition to the colour code, I'd like to make some of the guides bold. Here's a reproducible example

  library("ggpubr")
  library("reshape2")

iris.melt <- melt(iris)

ggboxplot(data = iris.melt, x = "variable", y= "value", add = "jitter",
          add.params = list(color = "Species"), legend = "bottom") +
theme(legend.text = element_text(face = "italic")) +
guides(col = guide_legend(override.aes = list(size=2), label.position = "bottom")) 

Which produces

iris boxplot

I tried highlighting only one species

ggboxplot(data = iris.melt, x = "variable", y= "value", add = "jitter",
          add.params = list(color = "Species"), legend = "bottom") +
theme(legend.text = element_text(face = c("plain","italic","plain")) +
guides(col = guide_legend(override.aes = list(size=2), label.position = "bottom"))

but "Vectorized input to element_text() is not officially supported."

Is there a way to customize individuals items in the legend?


Solution

  • I don't think there's a way to set the theme components separately, but there is a workaround, which is to use expressions for labels. That way you can make any single label bold:

    library("ggpubr")
    library("reshape2")
    
    iris.melt <- melt(iris)
    
    one_bold_label <- expression("Setosa", bold(paste("Versicolor")), "Virginica")
    
    ggboxplot(data = iris.melt, x = "variable", y= "value", add = "jitter",
              add.params = list(color = "Species"), legend = "bottom") +
      theme(legend.text = element_text(face = "italic")) +
      scale_colour_manual(labels = one_bold_label, values = c("#F8766D", "#00BA38", "#619CFF")) +
      scale_fill_manual(labels = one_bold_label, values = c("white", "white", "white"))
    

    Created on 2020-05-31 by the reprex package (v0.3.0)