6
votes

I would like to make a graph in ggplot2 with the x-axis on the log10 scale and the labels in regular rather than scientific notation with a minimum number of decimals. This means I would like to show 0.1 as 0.1 rather than 0.10 and 100 as 100 rather than 100.00.

I tried

df = data.frame(x =  c(1:10 %o% 10^(-3:2)), y = rnorm(60))

ggplot(df, aes(x=x, y=y))+
      geom_point()+scale_x_log10(labels=comma)

Unfortunately, this shows to many decimals.

@BenBolker answered a similar question previously and his code works fine for numbers without decimals, but if there are numbers smaller than 1 it seems to give the same results as labels=comma.

plain <- function(x,...) {
  format(x, ..., scientific = FALSE, trim = TRUE)
}

ggplot(df, aes(x=x, y=y))+
  geom_point()+scale_x_log10(labels=plain)
2

2 Answers

8
votes

Add drop0trailing = TRUE in plain.

plain <- function(x,...) {
  format(x, ..., scientific = FALSE, drop0trailing = TRUE)
}

To see other options for pretty printing, see ?format.

enter image description here

2
votes

Just wanted to add that instead of creating a separate plain function we can also use the scales package that provides a nice set of tools for ggplot2 scales and makes formatting log axis labels a breeze. Here's the reproducible code demonstrating some formatting options for log axis labels:

library(ggplot2)
library(scales)
library(patchwork)

df <- data.frame(x =  c(1:10 %o% 10^(-3:3)), y = rnorm(70))

base <- ggplot(df, aes(x, y)) + 
  geom_point()

p1 <- base + scale_x_log10(labels = label_number(drop0trailing = TRUE))
p2 <- base + scale_x_log10(labels = label_comma(drop0trailing = TRUE)) 
p3 <- base + 
  scale_x_log10(
    labels = label_dollar(drop0trailing = TRUE),
    # prevents axis label from going off the chart
    expand = expansion(mult = c(0.05, .06)) 
  )
p4 <- base + scale_x_log10(labels = trans_format("log10", label_math()))

(p1 + p2 + p3 + p4) + plot_annotation(tag_levels = "1", tag_prefix = "p")

Created on 2021-05-16 by the reprex package (v2.0.0)