2

I would like to italicize a part of a term in axis text (not title) in R ggplot2.

I have some bacterial species names that I should write in italic and besides I have the strain name that should be in plain text.

Here is an example of what I have:

My data frame looks like this

MyDF <- data.frame(Activity=rep(c("Activity 1", "Activity 2"), each = 3), 
                   Bacteria = c(sample(c("Escherichia coli Strain 1", "Escherichia coli Strain 2"), 3, TRUE, prob = c(0.3, 0.7)),
                                sample(c("Escherichia coli Strain 1", "Escherichia coli Strain 2"), 3, TRUE, prob = c(0.5, 0.5))))

MyDF
    Activity                  Bacteria
1 Activity 1 Escherichia coli Strain 2
2 Activity 1 Escherichia coli Strain 2
3 Activity 1 Escherichia coli Strain 1
4 Activity 2 Escherichia coli Strain 1
5 Activity 2 Escherichia coli Strain 2
6 Activity 2 Escherichia coli Strain 1

And the code used to generate the plot is:

MyPlot <- ggplot(data = MyDF, mapping = aes(x =Activity , y =Bacteria )) +
  xlab(label = "Activities") +
  ylab(label = "Strains") +
  theme(axis.text.y = element_text(face = "italic", size = 10, family = "serif"))

MyPlot                   

enter image description here

So my question is how to make "Escherichia coli" in italic and keep "Strain 1" in plain text.

Any help is really appreciated.

Best,

Najoua

Najoua
  • 81
  • 5

1 Answers1

2

You could use scale_y_discrete with expression and italic like this:

MyDF <- data.frame(Activity=rep(c("Activity 1", "Activity 2"), each = 3), 
                   Bacteria = c(sample(c("Escherichia coli Strain 1", "Escherichia coli Strain 2"), 3, TRUE, prob = c(0.3, 0.7)),
                                sample(c("Escherichia coli Strain 1", "Escherichia coli Strain 2"), 3, TRUE, prob = c(0.5, 0.5))))

library(ggplot2)
MyPlot <- ggplot(data = MyDF, mapping = aes(x =Activity , y =Bacteria )) +
  xlab(label = "Activities") +
  ylab(label = "Strains") +
  scale_y_discrete('Strains', labels = expression(~italic("Escherichia coli")~'Strain 1', ~italic("Escherichia coli")~'Strain 2'))

MyPlot 

Created on 2022-10-12 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • thank you for your reply. It worked like magic, but I got another question, please. How can I do the same thing when using facets in ggplot? When doing the same thing, the x text starts over when changing to the next facet. – Najoua Oct 13 '22 at 13:15
  • @NajouaMghazli, Good question. I would suggest to ask another question. – Quinten Oct 13 '22 at 15:03
  • I asked a new question in [link]https://stackoverflow.com/questions/74058524/how-to-italicize-some-words-in-a-sentence-in-x-axis-text-in-ggplot-facet but couldn't add the image – Najoua Oct 13 '22 at 15:45