gpt4 book ai didi

r - 将 ggplot 图设置为具有相同的 x 轴宽度和点图行之间的相同空间

转载 作者:行者123 更新时间:2023-12-04 22:31:12 25 4
gpt4 key购买 nike

更新了问题以合并已在 SO 上回答的部分解决方案

我正在使用 ggplot2 创建多个绘图,并使用 gridExtra 将这些绘图组合成一个带有多个面板的图形,所有面板都在一列中。我的问题是我无法在两个图中使点图行之间的空间保持一致。

library(ggplot2)
# data
dat1 <- data.frame(VARIABLES=c("Item 1", "Item 2 is a little longer"),
est=c(.3, .5),
min=c(.2, .4),
max=c(.4, .7))
dat2 <- data.frame(VARIABLES=c("Item 3",
"Item 4 is even longer if you can believe it",
"And there is a third item",
"And a fourth item"),
est=c(.3, .5, .3, .5),
min=c(.2, .4, .2, .4),
max=c(.4, .7, .4, .7))
dat <- c("dat1", "dat2")
labs <- c("Plot 1", "Plot2")
# create plots
count <- 1
for (i in dat) {
p <- ggplot(get(i), aes(x=reorder(as.character(VARIABLES), est),
y=est)) +
geom_pointrange(aes(ymin=min,
ymax=max),
linetype="dashed") +
geom_point(size=3) +
ylim(-1,1) +
theme_bw() +
labs(title = labs[count]) +
theme(legend.position="none") +
coord_flip()
assign(paste(i, "plot", sep="."), p)
count <- count+1
}
# combine plots
library(gridExtra)
# approach suggested by @baptise
# http://stackoverflow.com/questions/13294952/left-align-two-graph-edges-ggplot
gA <- ggplotGrob(dat1.plot)
gB <- ggplotGrob(dat2.plot)
maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
gA$widths[2:5] <- as.list(maxWidth)
gB$widths[2:5] <- as.list(maxWidth)
grid.arrange(gA, gB, ncol=1)

最佳答案

library(gridExtra)
library(grid)

gb1 <- ggplot_build(dat1.plot)
gb2 <- ggplot_build(dat2.plot)

# work out how many y breaks for each plot
n1 <- length(gb1$layout$panel_params[[1]]$y.labels)
n2 <- length(gb2$layout$panel_params[[1]]$y.labels)

gA <- ggplot_gtable(gb1)
gB <- ggplot_gtable(gb2)

g <- rbind(gA, gB)

# locate the panels in the gtable layout
panels <- g$layout$t[grepl("panel", g$layout$name)]
# assign new (relative) heights to the panels, based on the number of breaks
g$heights[panels] <- unit(c(n1,n2),"null")

grid.newpage()
grid.draw(g)

关于r - 将 ggplot 图设置为具有相同的 x 轴宽度和点图行之间的相同空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23863345/

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