How To Change Axis Tick Marks in R?

One of most common things one might do while making plots is to change tiny details of the plot to make them better. Often, one of such adjustments are changing x-axis tick mark label/text on a plot made with ggplot2 in R.

How to Change X-axis Tick Mark Label?
How to Change X-axis Tick Mark Label?

Let us use ggplot2 to make plot first and then fix its x-axis tick mark labels.

library(ggplot2)
library(tibble)

We will create a toy data frame using tibble with two column variables.

n <- 4
# create a tibble
df <- tibble(gender = c(rep("0",n), rep("1",n)),
             weight = c(rnorm(n,100,sd=5), rnorm(n,150,sd=5)))

A glimpse at the data frame shows that first column is a characeter variable and second is numeric.

>head(df)

gender  weight
&lt;chr&gt; . &lt;dbl&gt;
0	106.85479			
0	97.17651			
0	101.81564			
0	103.16431			
1	152.02134			
1	149.46938			

Let us make a boxplot with ggplot2 using the above dataframe.

# make boxplot with ggplot2
df %>% 
  ggplot(aes(x=gender,y=weight))+
  geom_boxplot(width=0.25) 

Note that in the boxplot we made right now, the x-axis variable gender has two levels, coded as 0 and 1. ggplot automatically found these levels and marked the X-axis tick mark labels as 0 and 1. You might know that the codes 0 & 1 correspond to Female and Male. And the plot is much easier read with Female and Male on the x-axis tick mark instead of 0 and 1.

Boxplot before fixing x-axis ticks mark

To change the x-axis tick mark label, from 0 & 1 to Female and Male here, we can add a layer scale_x_discrete() and specify the breaks currently used and specify the labels that we actually want, as shown below.

df %>% 
  ggplot(aes(x=gender,y=weight)) +
  geom_boxplot(width=0.25) +
  scale_x_discrete(breaks=c("0", "1"),
                      labels=c("Female", "Male"))

Voila, now the x-axis tick label text is Female and Male as we wanted.

Boxplot after fixing x-axis ticks_label

If you want to change y-axis tick mark labels, you can use scale_y_discrete().