abraham
abraham

Reputation: 743

how to use italic and normal font in a single label-word with ggplot2

I want to make a ggplot2 that in the same labels could use italic and normal font, example: wordX and wordY, word in italic, and X and Y in normal font: wordX and wordY

I tried something like:

data("mtcars")

mtcars$Type <- as.factor(c(rep("wordX", 16), rep("wordY", 16)))

head(mtcars, 3)
               mpg cyl disp  hp drat    wt  qsec vs am gear carb  Type
Mazda RX4     21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 wordX
Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 wordX
Datsun 710    22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 wordX

lbs = brk = levels(mtcars$Type)
lbs[match("wordX", brk)] = expression(italic("word")~X)
lbs[match("wordY", brk)] = expression(italic("word")~Y)

ggplot(mtcars, aes(factor(am), mpg, fill=Type)) +
     geom_col(position="dodge") + 
     theme(legend.text = element_text(size = 18),
           legend.title = element_text(size = 18)) +
     scale_fill_discrete(breaks=brk, labels=lbs)

enter image description here

in the example label word X and word Y are separated; how can I plot it together wordX and wordY

How can I make it ?

Thanks !!!

Upvotes: 0

Views: 347

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

Use asterisk (*) instead of tilde (~) in your expressions. The tilde symbol specifies a space, whereas the asterisk will act as a no-space separator.

lbs[match("wordX", brk)] = expression(italic("word")*X)
lbs[match("wordY", brk)] = expression(italic("word")*Y)

ggplot(mtcars, aes(factor(am), mpg, fill=Type)) +
     geom_col(position="dodge") + 
     theme(legend.text = element_text(size = 18),
           legend.title = element_text(size = 18)) +
     scale_fill_discrete(breaks=brk, labels=lbs)

enter image description here

Upvotes: 1

Related Questions