How to Change X and Y Axis Values from Real to Integers in ggplot2

How to Change X or Y-axis Values to Integers?
How to Change Y-axis Values to Integers?

When you make a plot with ggplot2, it automatically chooses appropriate range for x and y-axis values and it can be either floats or integers. In this post, we will see how to change X/Y-axis values to integers. In ggplot2, we can use scale_x_continuous() and scale_y_continuous() functions to change the axis values.

Let us first load tidyverse and load penguin datasets for making a plot with ggplot2 to illustrate the default behaviour of ggplot2 and how to change the axis values to integers.

library(tidyverse)
library(palmerpenguins)

Let us make scatter plot using ggplot2’s geom_point() function.

penguins %>%
  ggplot(aes(bill_length_mm, bill_depth_mm, color=species))+
  geom_point()

ggplot2 has automatically chose the range and the values for x-and y-axis. We can see that y-axis values are real numbers ranging from 15 to 20 with values at 15, 17.5 and 20.

Scatter plot with Float y-axis Values

How To Make Y-axis values to Integers? Use scale_y_continous()

Let us change the real values on the y-axis of the scatter plot to integer values. We can use the function scale_y_continuous() with breaks argument. Using breaks argument we specify how we want to have the axis breaks. In this example we provide vector with integer values we want to the plots to have on y-axis.

penguins %>%
  ggplot(aes(bill_length_mm, bill_depth_mm, color=species))+
  geom_point()+
  scale_y_continuous(breaks=c(14,16,18,20))

Here is how the plot looks like after specifying the integer values for y-axis using scale_y_continuous() function.

How to Change Y-axis Values to Integers?

How To Specify X-axis values in ggplot2?

Note that, in our example, x-axis values are already integers starting from 40 to 60. We can use scale_x_continuous() function to specify x-axis breaks.

In this example below we show x-axis values from 30 to 60, but at the increment of 5 instead of 10.

penguins %>%
  ggplot(aes(bill_length_mm, bill_depth_mm, color=species))+
  geom_point()+
  scale_y_continuous(breaks=seq(12,22,by=2))+
  scale_x_continuous(breaks=seq(30,60,by=5))
ggsave("how_to_display_specific_x_y_axis_values_ggplot2.png")

Now we have a plot with x and y-axis breaks with integer values that we manually specified.

How To Display Specific Axis Values with ggplot2?

Exit mobile version