Marco
Marco

Reputation: 275

Create a vector with multiple expressions

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)

Upvotes: 2

Views: 522

Answers (3)

Marina
Marina

Reputation: 995

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

Upvotes: 1

akrun
akrun

Reputation: 887058

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

Upvotes: 1

mt1022
mt1022

Reputation: 17289

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

Upvotes: 1

Related Questions