Home > database >  How to italicize some words in a sentence in axis text in R
How to italicize some words in a sentence in axis text in R

Time:10-14

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

CodePudding user response:

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

  • Related