2

In the following ggplot barchart. How can I generate a vector with multiple expressions automatically?

data <- data.frame(x = LETTERS[1:11], y = 10^(0:10))
z <- 0:10
y.labels <- sprintf(paste0("10^", z))
ggplot(data, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_y_log10(breaks = 10^(z), labels = y.labels)

I've tried with bquote(.(10^c(z))), but is not the desired result .

My only alternative is to do it manually, but it is not automatic:

y.labels <- expression("10"^0, "10"^1, "10"^2, "10"^3, "10"^4, "10"^5, "10"^6, "10"^7, "10"^8, "10"^9, "10"^10)

3 Answers 3

1

Try parse(text =, which will convert the character vector y.labels into the expected expression:

ggplot(data, aes(x, y)) +
    geom_bar(stat = "identity") +
    scale_y_log10(breaks = 10^(z), labels = parse(text = y.labels))
Sign up to request clarification or add additional context in comments.

Comments

1

We can use bquote with expression

y.labels <-  sapply(z, function(u) as.expression(bquote(10^.(u))))
ggplot(data, aes(x, y)) +
   geom_bar(stat = "identity") +
   scale_y_log10(breaks = 10^(z), labels =y.labels)

enter image description here

Comments

1

If you don't need to store both z and y.labels, you can use:

library(scales)
data <- data.frame(x = LETTERS[1:11], y = 10^(0:10))
ggplot(data, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_y_log10(breaks = trans_breaks(log10, function(x) 10^x, 10), 
                labels = trans_format(log10, math_format(10^.x)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.