【问题标题】:Aligning multiple plots using ggplot and gtable使用 ggplot 和 gtable 对齐多个图
【发布时间】:2019-02-28 18:27:16
【问题描述】:

我使用ggplot2 创建了两个图,我想使用gtable 同时显示它们。我有两个问题。首先是我希望面板大小在两个图中匹配。我已经使用gtable 完成了这项工作。第二个问题是我希望第一个图的宽度是第二个图的三倍。在使用ggtable 中的bind() 函数匹配面板大小时,我似乎无法弄清楚如何做到这一点。

下面提供了可重现的代码。

library(ggplot2)
library(gtable)

set.seed(2345)

mean1 <- runif(8, 700, 1000)
low1 <- mean1 - 100
high1 <- mean1 + 100
names1 <- paste0("really long name", 1:length(mean1))
df1 <- data.frame(mean = mean1,
  low = low1,
  high = high1,
  names = names1)

mean2 <- runif(2, 700, 1000)
low2 <- mean2 - 100
high2 <- mean2 + 100
names2 <- paste0("name", 1:length(mean2))
df2 <- data.frame(mean = mean2,
  low = low2,
  high = high2,
  names = names2)

plot1 <- ggplot(df1, aes(x = names, y = mean)) + 
  geom_errorbar(aes(ymin = low, ymax = high), width = 0) +
  geom_point() +
  scale_y_continuous(limits = c(.95*min(df1$low), 1.05*max(df1$high))) +
  xlab("") + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

plot2 <- ggplot(df2, aes(x = names, y = mean)) + 
  geom_errorbar(aes(ymin = low, ymax = high), width = 0) +
  geom_point() +
  scale_y_continuous(limits = c(.95*min(df1$low), 1.05*max(df1$high))) +
  xlab("") + 
  theme(axis.text.x = element_text(angle = 0, hjust = .5))

grob1 <- ggplotGrob(plot1) #Convert to gtable 
grob2 <- ggplotGrob(plot2) #Convert to gtable

grob <- cbind(grob1, grob2, size = "first") #Bind rt data

title <- textGrob("Title", gp = gpar(fontsize = 12)) #Add title
grob <- gtable_add_rows(
  grob, #gtable object
  heights = grobHeight(title) + padding, #height for new row
  pos = 0 #0 adds on top
)
grob <- gtable_add_grob(
  grob, #gtable object
  title, #grob to be added
  t = 1, l = 1, r = ncol(sG) #top, left, and right (18) extent of grob
)

grid.newpage()
grid.draw(grob)

如您所见,面板尺寸匹配,但图 1(左)和图 2(右)的宽度相同。我想合并这两个,使情节 1 比情节 2 宽三倍。我还想在两者之上添加一个标题,我已经在提供的代码中完成了。

【问题讨论】:

    标签: r ggplot2 gtable


    【解决方案1】:

    使用egg packageggarrange 函数,您可以用一行代码完成所有操作:

    egg::ggarrange(plot1, plot2, ncol = 2, top = "foo", widths = c(3, 1))
    

    【讨论】:

    • 这是一个更简单的解决方案!如果我想在同一个图中有几行图,每行都有一个标题,我将如何在同一个图中这样做?
    • @DavidJohnson 不可能,但您可以使用标签为每个图添加符号(就像在出版物中一样)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    相关资源
    最近更新 更多