10

For my legend in ggplot2 I have 2 categories, how do I italicize only 1 category and not the other?

As an example, consider the following plot. How can I set "Manual" in italics?

library(ggplot2)

ggplot(data = mtcars, aes(x = as.factor(am), fill = as.factor(am))) + 
  geom_bar() + 
  scale_fill_discrete(
    "Transmission",
    breaks = c(0, 1),
    labels = c("Automatic", "Manual")
  )

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

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104
Eswim
  • 101
  • 1
  • 1
  • 3

2 Answers2

18

You can use expression and italic to create italicized text on labels.

library(ggplot2)

ggplot(data = mtcars, aes(x = as.factor(am), fill = as.factor(am))) + 
  geom_bar() + 
  scale_fill_discrete(
    "Transmission",
    breaks = c(0, 1),
    labels = c("Automatic", expression(italic("Manual")))
  )

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

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104
r.bot
  • 5,309
  • 1
  • 34
  • 45
  • 3
    Really helpful response r.bot, thanks for posting! Just wanted to note if you're looking to get both legend entries aligned left you can add the following: ``+ theme(legend.text.align = 0)``. See this entry for more about that: https://stackoverflow.com/questions/26781676/align-legend-text-in-ggplot – user14353 Mar 06 '19 at 23:20
13

I have been working on a simpler and more flexible way to achieve this goal, via the ggtext package that enables markdown styling in ggplot. This is currently under development but should be released to CRAN soon (early 2020).

library(ggplot2) # may require: remotes::install_github("tidyverse/ggplot2")
library(ggtext)  # remotes::install_github("clauswilke/ggtext")

ggplot(data = mtcars, aes(x = as.factor(am), fill = as.factor(am))) + 
  geom_bar() + 
  scale_fill_discrete(
    "Transmission",
    breaks = c(0, 1),
    labels = c("Automatic", "*Manual*")
  ) +
  theme(legend.text = element_markdown())

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

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104