简体   繁体   中英

Number formatting with log10 scale in ggplot

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM