gpt4 book ai didi

r - 调整 ggplot2 中轴文本的 "margin"空间

转载 作者:行者123 更新时间:2023-12-04 12:27:08 30 4
gpt4 key购买 nike

ggplot 中的哪个属性(如果有)控制
宽度 (或空格量)轴文本?

在下面的示例中,我的最终目标是“插入”顶部图形的左侧,使其与底部图形对齐。

我试过 theme(plot.margin=..)但这会影响整个情节的边缘。facet 'ing 也无济于事,因为 y 上的尺度不同。

作为最后的手段,我意识到我可以修改轴文本本身,但是我还需要计算每个图形的切割。

enter image description here

可重现的例子:

library(ggplot2)
library(scales)

D <- data.frame(x=LETTERS[1:5], y1=1:5, y2=1:5 * 10^6)

P.base <- ggplot(data=D, aes(x=x)) +
scale_y_continuous(labels=comma)

Plots <- list(
short = P.base + geom_bar(aes(y=y1), stat="identity", width=.5)
, long = P.base + geom_bar(aes(y=y2), stat="identity", width=.5)
)

do.call(grid.arrange, c(Plots, ncol=1, main="Sample Plots"))

最佳答案

这是一种解决方案。

这个想法是从“Having horizontal instead of vertical labels on 2x1 facets and splitting y-label”中借来的。
定义一个函数

align_plots1 <- function (...) {
pl <- list(...)
stopifnot(do.call(all, lapply(pl, inherits, "gg")))
gl <- lapply(pl, ggplotGrob)
bind2 <- function(x, y) gtable:::rbind_gtable(x, y, "first")
combined <- Reduce(bind2, gl[-1], gl[[1]])
wl <- lapply(gl, "[[", "widths")
combined$widths <- do.call(grid::unit.pmax, wl)
grid::grid.newpage()
grid::grid.draw(combined)
}

short <- P.base + geom_bar(aes(y=y1), stat="identity", width=.5)
long <- P.base + geom_bar(aes(y=y2), stat="identity", width=.5)

#Now, align the plots
align_plots1(short, long)

这是输出。

enter image description here

关于r - 调整 ggplot2 中轴文本的 "margin"空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22291088/

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