Notification texts go here Contact Us Buy Now!

Remove trailing zeros in ggplot axis

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:

enter image description here

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.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.