Remove trailing zeros in ggplot axis
Asked Answered
D

2

5

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).

enter image description here If I have to set all labels in each graph manually that would be very cumbersome.

Damselfish answered 26/6, 2019 at 10:58 Comment(2)
The attached image is too small to see what you refer to.Stripy
@Stripy I have rescaled the image. All zero values have trailing zeros as shown in the image.Damselfish
S
7

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:

enter image description here

Stripy answered 26/6, 2019 at 12:29 Comment(4)
How can I combine that with labels = comma?Because
really nice answer, however it turns 0.0001 into 1e-4Danieledaniell
Thank you!! I have been looking to transform 1.00 into 1 but to keep 0.25!!Pastel
@Pastel see my answer belowBurgle
B
0

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

Burgle answered 25/1 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.