Home > Blockchain >  In ggplot2 on log10 scale, can axis label accuracy vary?
In ggplot2 on log10 scale, can axis label accuracy vary?

Time:02-11

I'm drawing a plot with a log10 x-axis, with limits from 0.01 to 100. By default, the axis is displayed in scientific notation.

If I define the label using comma_format(), it the ticks mark 0.01, 0.10, 1.00, 10.00 and 100.00.

However, I want the labels to be 0.01, 0.1, 1, 10, 100.

Is there any way to vary with accuracy?

CodePudding user response:

You can use gsub() with a regex pattern to remove trailing zeroes and optionally a separator.

The expression below has the following meaning:

  • 0 $ one or more zeroes at the end of the string.
  • \\.? possibly a period (the dashes indicate literal periods instead of the regex wildcard). By placing this before the zeroes, we only seek to remove periods followed by zeroes, which excludes e.g. 0.01.
library(scales)
library(ggplot2)

df <- data.frame(x = 10^seq(-2, 2, length.out = 10))

ggplot(df, aes(x, x))  
  geom_point()  
  scale_y_log10(
    labels = ~ gsub("\\.?0 $", "", comma(.x))
  )

Created on 2022-02-09 by the reprex package (v2.0.1)

  • Related