在下面的ggplot条形图中。如何自动生成具有多个表达式的向量?
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)
我尝试使用bquote(.(10^c(z)))
,但不是理想的结果。
我唯一的选择是手动完成,但不是自动的:
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)
答案 0 :(得分:1)
尝试parse(text =
,它会将字符向量y.labels
转换为预期的表达式:
ggplot(data, aes(x, y)) +
geom_bar(stat = "identity") +
scale_y_log10(breaks = 10^(z), labels = parse(text = y.labels))
答案 1 :(得分:1)
我们可以将bquote
与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)
答案 2 :(得分: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)))