How to Change Number of Axis Ticks in ggplot2 (With Examples)


You can use the following basic syntax to change the number of axis ticks on plots in ggplot2:

p +
  scale_x_continuous(n.breaks=10) +
  scale_y_continuous(n.breaks=10)

The following example shows how to use this syntax in practice.

Example: Change Number of Axis Ticks in ggplot2

Suppose we have the following data frame in R:

#create data frame
df <- data.frame(x=c(1, 2, 4, 5, 6, 8, 12, 14, 19),
                 y=c(2, 5, 7, 8, 14, 19, 22, 28, 36))

#view data frame
df

   x  y
1  1  2
2  2  5
3  4  7
4  5  8
5  6 14
6  8 19
7 12 22
8 14 28
9 19 36

If we create a scatter plot, ggplot2 will automatically pick a suitable number of ticks for both the x-axis and y-axis:

library(ggplot2)

#create scatter plot
ggplot(df, aes(x=x, y=y)) +
  geom_point(size=2)

However, we can use the n.breaks argument to specify the exact number of ticks to use on both axes:

library(ggplot2)

#create scatter plot with custom number of ticks
ggplot(df, aes(x=x, y=y)) +
  geom_point(size=2) +
  scale_x_continuous(n.breaks=10) +
  scale_y_continuous(n.breaks=10)

Notice that the number of ticks on both axes has increased.

Also note that you can change the number of ticks on just one axis if you’d like:

library(ggplot2)

#create scatter plot with custom number of ticks on x-axis only
ggplot(df, aes(x=x, y=y)) +
  geom_point(size=2) +
  scale_x_continuous(n.breaks=20)

In this example, ggplot2 chooses the number of ticks to use on the y-axis but the number of ticks on the x-axis is determined by the number in the n.breaks argument.

Additional Resources

The following tutorials explain how to perform other common tasks in ggplot2:

How to Rotate Axis Labels in ggplot2
How to Set Axis Breaks in ggplot2
How to Set Axis Limits in ggplot2
How to Change Legend Labels in ggplot2

Leave a Reply

Your email address will not be published. Required fields are marked *