Reputation: 333
there must surely be another way of removing trailing zeros in y axis tick labels than specifiying each label indivdiually with labels=c("0",...)
.
I have a number of graphs plotted in a grid and there are all trailing zeros in the y axis, in particular for the zero value (see image).
If I have to set all labels in each graph manually that would be very cumbersome.
Upvotes: 5
Views: 2726
Reputation: 9506
If you don't want any trailing zeros, you can use labels = scales::label_number(drop0trailing=TRUE)
in a scale_*
function:
library(ggplot2)
iris |> ggplot(aes(x = Petal.Length, y= Petal.Width)) +
geom_point() +
scale_y_continuous(labels = scales::label_number(drop0trailing=TRUE))
Here, I used scales::label_number
(the scales
package is anyway required by ggplot2
) with the drop0trailing=TRUE
parameter, which will be passed down to base::format
which in turn will pass it down to base::prettyNum
where this functionality is finally documented:
?prettyNum
:
drop0trailing
logical, indicating if trailing zeros, i.e., "0" after the decimal mark, should be removed; also drops "e+00" in exponential formats. [...]
For reference, this is how the y axis labels would look by default:
iris |> ggplot(aes(x = Petal.Length, y= Petal.Width)) +
geom_point()
Created on 2024-01-25 with reprex v2.0.2
Upvotes: 0
Reputation: 33782
Try adding this to your ggplot
:
+ scale_y_continuous(labels = function(x) ifelse(x == 0, "0", x))
Example data:
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))
Result:
Upvotes: 7