Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log axis labels in ggplot2: Show only necessary digits?

Tags:

plot

r

ggplot2

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)
like image 576
bee guy Avatar asked May 18 '18 14:05

bee guy


1 Answers

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

like image 83
hpesoj626 Avatar answered Oct 07 '22 22:10

hpesoj626