在R中,如何判断ggplot对象上的比例是对数还是线性?
我有许多ggplot对象,我希望在每个绘图上的相同相对位置打印一些文本(不同的绘图),而不考虑比例。我想让它变得简单的是在R中,如何判断ggplot对象上的比例是对数还是线性?,r,ggplot2,R,Ggplot2,我有许多ggplot对象,我希望在每个绘图上的相同相对位置打印一些文本(不同的绘图),而不考虑比例。我想让它变得简单的是 定义一个重缩放函数(称为sx)以获取我想要的相对位置,并返回绘图x轴上的位置 然后将文本添加到绘图中 plt假设我们有一个预构建图列表: linear <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) + geom_point() log <- linear + scale_y
plt假设我们有一个预构建图列表:
linear <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) +
geom_point()
log <- linear + scale_y_log10()
linear <- ggplot_build(linear)
log <- ggplot_build(log)
plotlist <- list(a = linear, b = log)
或者,如果您更喜欢直截了当的答案:
log$plot$scales$scales[[1]]$trans$name
非常感谢。这正是我想要的。
plt <- plt + annotate("text", x=sx(0.95), ....)
linear <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) +
geom_point()
log <- linear + scale_y_log10()
linear <- ggplot_build(linear)
log <- ggplot_build(log)
plotlist <- list(a = linear, b = log)
out <- lapply(names(plotlist), function(i) {
# Grab plot, panel parameters and scales
plot <- plotlist[[i]]
params <- plot$layout$panel_params[[1]]
scales <- plot$plot$scales$scales
# Only keep (continuous) position scales
keep <- vapply(scales, function(x) {
inherits(x, "ScaleContinuousPosition")
}, logical(1))
scales <- scales[keep]
# Grab relevant transformations
out <- lapply(scales, function(scale) {
data.frame(position = scale$aesthetics[1],
# And now for the actual question:
transformation = scale$trans$name,
plot = i)
})
out <- do.call(rbind, out)
# Grab relevant ranges
ranges <- params[paste0(out$position, ".range")]
out$min <- sapply(ranges, `[`, 1)
out$max <- sapply(ranges, `[`, 2)
out
})
out <- do.call(rbind, out)
out
position transformation plot min max
1 x identity a 1.8800000 4.520000
2 y identity a 4.1200000 8.080000
3 y log-10 b 0.6202605 0.910835
4 x identity b 1.8800000 4.520000
log$plot$scales$scales[[1]]$trans$name
[1] "log-10"