rggplot2legenditalic

How to italicize only some elements of ggplot legend?


I need to set to italic all elements of the legend instead of the last one ("Others"). My current code for graph design is:

p <- ggplot(D, aes(x=factor(Habitat, levels=c("Water","Soil")), y=RA, fill=factor(Species)))+
  geom_bar(stat = "identity", position = "stack", width = 0.5, colour='black', size=0.1)+
  scale_fill_manual(name="Species", values=myColour)+
  guides(fill=guide_legend(ncol=1))+
  xlab(" ")+
  ylab("[ % ]")+
  ylim(0,100)+
  theme(aspect.ratio=2,
        panel.background = element_rect(fill = "white"),
        panel.grid.minor = element_blank(),
        plot.title = element_text(size=35, face="bold", vjust = 0, hjust = -0.1),
        legend.title = element_text(size=35, colour = "black", face="bold"),
        legend.text = element_text(size=35, colour = "black"),
        legend.key.size = unit(1, 'cm'),
        legend.key = element_rect(size = 15, color = "white"),
        legend.key.height = unit(2, "cm"),
        legend.key.width = unit(2, "cm"),
        legend.box.spacing = unit(1.5, "cm"),
        axis.title = element_text(size=30, face="bold"),
        axis.title.x = element_text(vjust = -3),
        axis.text = element_text(size=25, colour = "black"),
        axis.line = element_line(colour = "black", size = 0.9))+
  guides(fill = guide_legend(override.aes = list(linetype = "solid", color = "white", size = 5))))

Using scale_fill_manual, I didn't find any other example. Thank you


Solution

  • Using the ggtext package, you can apply markdown to text elements. In markdown, you can italicise a part by surrounding them with asterisks *. Example with the iris dataset:

    library(ggplot2)
    library(ggtext)
    
    df <- transform(iris, Species = as.character(Species))
    # Introduce a dummy "Other" category by sampling 50 observations
    df$Species[sample(nrow(df), 50)] <- "Other"
    # Conditionally apply markdown if Species is not "Other"
    df$Species <- with(df, ifelse(Species == "Other", "Other", 
                                  paste0("*Iris ", Species, "*")))
    
    ggplot(df, aes(Sepal.Length, Sepal.Width)) +
      geom_point(aes(colour = Species)) +
      theme(legend.text = element_markdown()) # <- Set plot theme element
    

    Alternatively, you might want to provide the markdown formatting step as a function to the label argument of the scale. This can be convenient if you've introduced some ordering to the colours that should be preserved.

    df <- transform(iris, Species = as.character(Species))
    df$Species[sample(nrow(df), 50)] <- "Other"
    
    ggplot(df, aes(Sepal.Length, Sepal.Width)) +
      geom_point(aes(colour = Species)) +
      scale_colour_discrete(
        labels = function(x) {
          ifelse(x == "Other", "Other", paste0("*Iris ", x, "*"))
        }
      ) +
      theme(legend.text = element_markdown())