how to only display decimals in ggplot axis tick labels?

Viewed 34

How can I get ggplot to display only decimals in the axis tick labels?

Consider a toy dataframe like the following, for which all the variables are < 1 in absolute value:

set.seed(42)

x <- rnorm(n=500, sd = 0.1)
y <- 0.05 + 2*x + rnorm(n=500, sd = 0.05)
df <- data.frame(x,y)

summary(df)

library(ggplot2)
ggplot(data = df, aes(x = x, y = y)) +
    geom_point()

enter image description here

Is it possible to have .xx instead of 0.xx on the axis?

1 Answers

You can pass a function to the labels argument of the scale_x_continuous(), in this case a lambda style function:

ggplot(data = df, aes(x = x, y = y)) +
  geom_point() + 
  scale_x_continuous(labels=~sub("^(-?)0.", "\\1.", sprintf("%.1f", .x)))
Related