If you have a ggplot with an axis that has trailing zeros, you can remove them using the following code:
+ scale_y_continuous(labels = function(x) ifelse(x == 0, "0", x))
This code will check if the value of the axis is equal to 0. If it is, it will replace it with the string "0". Otherwise, it will leave the value unchanged.
Here is an example of how to use this code:
data.frame(x = 1:6,
y = seq(0, 0.05, 0.01)) %>%
ggplot(aes(x, y)) +
geom_point() +
scale_y_continuous(labels = function(x) ifelse(x == 0, "0", x))
This code will create a ggplot with the following axis:
As you can see, the trailing zeros have been removed from the axis.
Another way to remove trailing zeros from an axis is to use the drop0trailing
parameter in the scale_y_continuous()
function. This parameter is set to FALSE
by default, but you can set it to TRUE
to remove trailing zeros.
ggplot(aes(x, y)) +
geom_point() +
scale_y_continuous(drop0trailing = TRUE)
This code will produce the same result as the previous code.
Finally, you can also use the format()
function to remove trailing zeros from an axis. The format()
function can be used to format the values of an axis in a variety of ways. To remove trailing zeros, you can use the following code:
ggplot(aes(x, y)) +
geom_point() +
scale_y_continuous(labels = scales::format_number(accuracy = 2))
This code will round the values of the axis to two decimal places, which will remove any trailing zeros.