Zoe
Zoe

Reputation: 1000

ggplot - logarithmic axis labels with defined decimal places

I have some data which has quite some large values and is spread across a large value range. Therefore, I want to display the data on a logarithmic scale. I found the package scales and managed to get this plot:

enter image description here

With this dummy data:

dummy <- data.frame(
  x = "A",
  y = 10^runif(100, min = 1, max = 2.5)
)

And this code:

ggplot(data = dummy, aes(x = x, y = y)) +
  geom_boxplot() +
  scale_y_continuous(
    trans = log10_trans(),
    breaks = trans_breaks("log10", function(x) 10^x),
    labels = trans_format("log10", math_format(10^.x))
  ) +
  theme(
    text = element_text(size = 16)
  )

However, I would like the numbers in the superscript to always have the same amount of decimal places, lets say 1. How can I achieve this with ggplot2? I tried to add format(..., nsmall = 1) around different parts of the label argument, but this does not work. It seems like I don't really understand the trans_format() function. Can anyone help me?

E.g.: I want the axis to be labeled with 102.0, not with 102

Upvotes: 2

Views: 759

Answers (2)

teunbrand
teunbrand

Reputation: 37913

The math_format() function has a format argument wherein you can stack another function to format your numbers.

library(ggplot2)
library(scales)

dummy <- data.frame(
  x = "A",
  y = 10^runif(100, min = 1, max = 2.5)
)

ggplot(data = dummy, aes(x = x, y = y)) +
  geom_boxplot() +
  scale_y_continuous(
    trans = log10_trans(),
    breaks = trans_breaks("log10", function(x) 10^x),
    labels = math_format(
      format = function(x){number(log10(x), accuracy = 0.1)}
    )
  ) +
  theme(
    text = element_text(size = 16)
  )

Created on 2021-09-09 by the reprex package (v2.0.1)

Upvotes: 3

Lenn
Lenn

Reputation: 1469

Likely not a very helpful answer, but maybe something in this direction could help:

dummy <- data.frame(
  x = "A",
  y = 10^runif(100, min = 1, max = 2.5)
)



ggplot(data = dummy, aes(x = x, y = y)) +
  geom_boxplot() +
  scale_y_continuous(
    trans = log10_trans(),
    breaks = trans_breaks("log10", function(x)
      10 ^ x),
    labels = function(y){sprintf("10^%.1f", y)}
  ) +
  theme(text = element_text(size = 16),
        axis.text = element_markdown())

which gives this:

enter image description here

Upvotes: 2

Related Questions