Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

italics and line breaks in ggplot2

Tags:

r

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")
like image 571
Nigel Haywood Avatar asked Nov 15 '25 20:11

Nigel Haywood


1 Answers

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

like image 192
Mikko Avatar answered Nov 17 '25 12:11

Mikko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!