简体   繁体   中英

Conditional formatting of decimals in tick labels based on number size in ggplot r

In my ggplot x axis tick labels, I would like to format numbers between 0 to 1 with one decimal place (like 0.1, 0.2, 0.5 etc), but if the number is 1 or above, I would like to just show the number as an integer (1,2,3,4).

I would also like to format the tick label with an X at the end to signify the labels are multiplier factors. The ideal result for the X axis tick labels would look like

0.1X 0.2X 0.5X 1X 2X 3X 4X

Here's a minimal example of an example dataset

set.seed(42)
data.frame(exp=rexp(100,5)*10) %>%
  ggplot(aes(x=exp)) +
  geom_density() +
  scale_x_log10(breaks = c(0.1, 0.2, 0.3, 0.5, 1, 2, 4, 6))

在此输入图像描述

I saw this answer, but I can't figure out how to make it work with my x axis.

You want 1 significant figure so you can use signif() :

data.frame(exp=rexp(100,5)*10) %>%
    ggplot(aes(x=exp)) +
    geom_density() +
    scale_x_log10(breaks = c(0.1, 0.2, 0.3, 0.5, 1, 2, 4, 6), 
                  labels = function(b) paste0(signif(b, 1), "X"))

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