Home > Software engineering >  Number formatting with log10 scale in ggplot
Number formatting with log10 scale in ggplot

Time:01-28

I transformed the axis number to the log scale, but I also wanted to set number accuracy (decimal places) and decimal marks (dot or comma). My code is reproducible as follows.

library(tidyverse)

mtcars %>% ggplot(aes(x=mpg, y=disp)) 
  geom_point()  
  scale_x_continuous(trans = log_trans(),
                            breaks = trans_breaks("log", function(x) exp(x), n.breaks = 5),
                            labels = trans_format("log", math_format(e^.x)))

Note that decimal places and marks of x-axis cannot be configured.

I tried to add a second scale_x_continuous with the wanted configurations, but it failed.

CodePudding user response:

You could use the format argument of math_format to change the number of decimals like this:

library(tidyverse)
library(scales)
mtcars %>% ggplot(aes(x=mpg, y=disp)) 
  geom_point()  
  scale_x_continuous(trans = log_trans(),
                     breaks = trans_breaks("log", function(x) exp(x), n.breaks = 5),
                     labels = trans_format("log", math_format(e^.x, format = function(x) number(x, accuracy = 0.1))))

Created on 2023-01-27 with reprex v2.0.2

  • Related