How to italicize boxplot label in R using ggplot2?

R ProgrammingServer Side ProgrammingProgramming

Like every other tool for statistical analysis R does not display the labels of a boxplot in italics, thus if we want to do this, we need to do it manually. In ggplot2, we have a function scale_x_discrete that can be used to change the default font to italic using expression function.

Example

 Live Demo

Consider the below data frame −

set.seed(121)
x<−sample(c("Male","Female"),5000,replace=TRUE)
y<−rnorm(5000,10,1)
df<−data.frame(x,y)
head(df,20)

Output

    x       y
1 Female  8.543501
2 Female  11.235843
3 Female  10.619936
4 Male    11.913005
5 Female   9.454871
6 Male    11.050363
7 Male    11.345901
8 Male     9.988700
9 Male     9.470426
10 Male    9.922687
11 Male   10.563857
12 Male   10.701888
13 Female 10.433731
14 Male    9.324858
15 Female 11.511777
16 Female  8.728229
17 Male   10.363001
18 Female 11.160330
19 Male   11.342272
20 Female 10.113535

Loading ggplot2 package and creating boxplot of y for Male and Females −

Example

library(ggplot2)
ggplot(df,aes(x,y))+geom_boxplot()

Output

Creating the boxplot with italic labels on X−axis −

ggplot(df,aes(x,y))+geom_boxplot()+scale_x_discrete(labels=expression(italic(Female),italic(Male)))

Output

raja
Published on 17-Oct-2020 12:56:37
Advertisements