How to italicize part (one or two words) of an axis title

RGgplot2Axis

R Problem Overview


Is there any way to change the style of part of an axis title while keep the rest part unchanged? In my case, How could I italicize
"bacteria X" in the y-axis title? To my knowledge, the command theme(axis.title.y=element_text(face="italic")) can only change the whole y-aixs title, is it?

ggplot(fig1,aes(x=cf,y=Freq,fill=Var1)) +
geom_bar(stat="identity") +
labs(x="Groups",y="No. of bacteria X isolates with corresponding types",fill="Var1") +
theme(axis.title.y=element_text(face="italic"))

R Solutions


Solution 1 - R

You could make an expression like this:

my_y_title <- expression(paste("No. of ", italic("bacteria X"), " isolates with corresponding types"))
.... + labs(y=my_y_title)

Solution 2 - R

This can be achieved using element_markdown() from the ggtext package.

ggplot(fig1, aes(cf, Freq, fill = Var1)) +
  geom_bar(stat = "identity") +
  labs(
    x = "Groups",
    y = "No. of *bacteria X* isolates with corresponding types",
    fill = "Var1"
  ) +
  theme(axis.title.y = ggtext::element_markdown())

Notice the * around bacteria X in the y axis title. Setting axis.title.y to element_markdown has the effect that the axis title is rendered as markdown. Thus, text inside * will be displayed in italics.

An even easier solution is using the mdthemes package which provides themes that interpret text as makrdown out of the box, i.e. no need to call theme. Here's an example.

ggplot(mtcars, aes(hp, mpg)) +
  geom_point() +
  mdthemes::md_theme_classic() +
  labs(title = "**Bold Title**", x = "*Italics axis label*")

enter image description here

Solution 3 - R

I believe RFelber's suggestion is what you are after. Try this:

labs(x="Groups",
     y=expression('No. of'~italic(bacteria X)~'isolates with corresponding types'),
     fill="Var1")

I did not need to use the bquote() function. The tildes produce single spaces for terms that are outside of the quotes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionezeView Question on Stackoverflow
Solution 1 - RHerokaView Answer on Stackoverflow
Solution 2 - RThomas NeitmannView Answer on Stackoverflow
Solution 3 - RTCSView Answer on Stackoverflow