gpt4 book ai didi

r - 将表达式与 sprintf 结合起来,在 R 中生成用于 ggplot/plot-labeling 的结果

转载 作者:行者123 更新时间:2023-12-04 17:52:36 26 4
gpt4 key购买 nike

我想使用 expression结合 sprintf -ggplot2 中标记的结果或 plot .

所以我尝试了(无意义的例子,只是为了说明问题):

require(ggplot2)
test <- 2
ggplot(data = iris, aes(x = Sepal.Length)) +
geom_bar() +
scale_x_continuous(name = expression(""<=sprintf(paste0("%.", test, "f"), pi)))

显然,这不起作用(仅评估 <=pi ),即使两个单独的元素都起作用。是否有可能重写表达式,使其与组合一起使用?我已经尝试包括 ~eval(parse(text = ...))但这些也不起作用。最后:必须集成 test -对象进入sprintf对我来说。

提前致谢!

编辑所以这是一个更好的例子。我以为我把另一个做得尽可能小,但显然它不够具体。对不起。希望有可能了解我的问题。谢谢!

require(ggplot2)
require(scales)

# data
ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))
values <- data.frame(id = ids,
value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5))
positions <- data.frame(id = rep(ids, each = 4),
x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2))
datapoly <- merge(values, positions, by = c("id"))

# plot preperation (for many ggplots is especially decimals output of a function)
decimals <- 2
lim_min <- 3.1
lim_max <- 3.4
breaks <- seq(lim_min, lim_max, (lim_max - lim_min)/4)
labels <- c(paste0("<", sprintf(paste0("%.", decimals, "f"), breaks[1])),
sprintf(paste0("%.", decimals, "f"), breaks[2]),
sprintf(paste0("%.", decimals, "f"), breaks[3]),
sprintf(paste0("%.", decimals, "f"), breaks[4]),
paste0(">", sprintf(paste0("%.", decimals, "f"), breaks[5])))

# plot
ggplot(datapoly, aes(x = x, y = y)) +
geom_polygon(aes(fill = value, group = id)) +
scale_fill_gradient(limits = c(3.1, 3.4),
low = "green", high = "orange",
breaks = breaks,
labels = labels,
oob = squish)

现在轴刻度标签是 "<3.10" "3.17" "3.25" "3.33" ">3.40"我想要 "<=3.10" "3.17" "3.25" "3.33" ">=3.40" , 而不是 >=<=使用像 here 这样的数学符号和 here

最佳答案

所以在baptiste的提示下我自己找到了一个substitute的解决方案。改变

labels <- c(substitute(""<=a, list(a =sprintf(paste0("%.", decimals, "f"), breaks[1]))),
sprintf(paste0("%.", decimals, "f"), breaks[2]),
sprintf(paste0("%.", decimals, "f"), breaks[3]),
sprintf(paste0("%.", decimals, "f"), breaks[4]),
substitute("">=a, list(a =sprintf(paste0("%.", decimals, "f"), breaks[5]))))

在上面的后一个例子中,结果是我想要的!谢谢!

关于r - 将表达式与 sprintf 结合起来,在 R 中生成用于 ggplot/plot-labeling 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43363168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com