Nigel Haywood
Nigel Haywood

Reputation: 43

italics and line breaks in ggplot2

I'm trying to fit headings with an italic n and a line break using scale_x_discrete. Here's an example using mpg. Without trying to get an italic, the manufacturer's name appears centralised under the tick, with the n = line centralised below that. Which is what I want. I cannot reproduce that producing an italic with bquote or expression. As an italic n must be one of the commonest symbols for a caption, I assume I'm missing something obvious. Can anyone help, please?

mpg2<- subset(mpg, manufacturer %in% c("audi", "toyota"))
mpg3<- subset(mpg2, class %in% c("compact", "midsize"))

cbp <- c("#E69F00", "#56B4E9")
xsub1 <-bquote(paste("Audi\n", italic("n"), " = 18 (15, 3)"))
xsub2 <-bquote(paste("Toyota\n", italic("n"), " = 19 (12, 7)"))


ggplot (mpg3, aes (x=manufacturer, y=hwy, colour=class))+
  geom_boxplot()+
  labs (colour = NULL)+
  xlab("")+
  ylab("highway mpg")+
  scale_colour_manual (labels = c ("compact","midsize"),
                        values = c(cbp))+
  scale_x_discrete(labels=c(xsub1, xsub2)) +
  theme (legend.position = "bottom")

Upvotes: 4

Views: 1037

Answers (1)

Mikko
Mikko

Reputation: 7755

You can use the atop() function.

mpg2 <- subset(mpg, manufacturer %in% c("audi", "toyota"))
mpg3 <- subset(mpg2, class %in% c("compact", "midsize"))

cbp <- c("#E69F00", "#56B4E9")

xsub1 <- ~ atop(paste("Audi"), paste(italic("n"), " = 18 (15, 3)"))
xsub2 <- ~ atop(paste("Toyota"), paste(italic("n"), " = 19 (12, 7)"))

ggplot(mpg3, aes (x = manufacturer, y = hwy, colour=class))+
  geom_boxplot()+
  labs (colour = NULL)+
  xlab("")+
  ylab("highway mpg")+
  scale_colour_manual(labels = c("compact","midsize"), values = c(cbp))+
  scale_x_discrete(labels = c(xsub1, xsub2)) +
  theme (legend.position = "bottom")

enter image description here

The solution is from @Jaap

Upvotes: 4

Related Questions