3

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))

enter image description here

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

Harry M
  • 1,848
  • 3
  • 21
  • 37

1 Answers1

4

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"))
Marius
  • 58,213
  • 16
  • 107
  • 105