4

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")
pogibas
28.5k21 gold badges92 silver badges120 bronze badges
asked Feb 28, 2019 at 18:38

1 Answer 1

4

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

answered Feb 28, 2019 at 19:56
Sign up to request clarification or add additional context in comments.

2 Comments

That works extremely well in all the cases I've needed it so far: very many thanks
I'm asked to avoid comments like thanks, @Tung: but thanks!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.