gpt4 book ai didi

ggplot2 - ggplot grobs 与 tableGrob 对齐

转载 作者:行者123 更新时间:2023-12-02 01:21:02 28 4
gpt4 key购买 nike

我很难找到对齐 ggplot grob 和 table grob 的解决方案。我试图按照说明here但仍然没有给出我想要的结果。

library(grid)
library(gridExtra)
library(ggplot2)
library(tibble)
library(gtable)
dat <- tibble::rownames_to_column(mtcars, "car") #convert rownames to first col

plot1 <- ggplot(dat, aes(car, mpg)) +
geom_bar(stat = "identity") +
coord_flip()

g1 <- ggplotGrob(plot1)
tb1 <- tableGrob(dat$cyl)
g1 <- gtable_add_cols(g1, unit(0.2, "npc"))
g1 <- gtable_add_grob(g1, grobs = tb1, t=3, l=ncol(g1), b=6, r=ncol(g1))

grid.newpage()
grid.draw(g1)
我希望表格中的每个单元格都与直方图中的相关条对齐,但仍然无法理解如何从布局中实现 t,l,b,r。 This is the output I got
enter image description here

最佳答案

当我尝试使用 ggplot2 在 R 中制作类似森林图的东西时,我遇到了与上述类似的问题,但没有找到任何其他解决方案适合我的需求。上面的答案对我不起作用 - table 没有出现。所以我在代码上编写了一个不太漂亮的解决方案,但我实际上有点喜欢干净的视觉输出。

我喜欢这个解决方案的地方是:

  • 我不是在表格中对齐一组自定义文本,而是在右侧的图中对齐,其中对齐与图中的每个文本条目和每个标签相匹配。
  • 我使用居中的 ggtitle 在每组文本上方对齐“列标题”。这些可以是任何类型的字符串(在我的实际使用中,我有点估计和置信区间)。
  • library(gridExtra)
    library(ggplot2)

    dat <- data.frame(
    label = c("A", "B", "C"),
    point_est = c(1,2,3),
    lb_ci = c(.5, 1.5, 2.5),
    ub_ci = c(1.5, 2.5, 3.5),
    n = c(50, 100, 150),
    total = c(75, 150, 200)
    )

    plot1 <- ggplot(dat, aes(x=point_est, y=label)) +
    geom_point() +
    geom_errorbarh(aes(xmin=lb_ci, xmax=ub_ci), height=.5) +
    ggtitle("Some measure") +
    ylab(NULL) + xlab("some effect estimate")

    tab_base <- ggplot(dat, aes(y=label)) +
    ylab(NULL) + xlab(" ") +
    theme(plot.title = element_text(hjust = 0.5, size=12), ## centering title on text
    axis.text.x=element_text(color="white"), ## need text to be printed so it stays aligned with figure but white so it's invisible
    axis.line=element_blank(),
    axis.text.y=element_blank(),axis.ticks=element_blank(),
    axis.title.y=element_blank(),legend.position="none",
    panel.background=element_blank(),panel.border=element_blank(),panel.grid.major=element_blank(),
    panel.grid.minor=element_blank(),plot.background=element_blank())

    tab1 <- tab_base +
    geom_text(aes(x=1, label=n)) +
    ggtitle("n")

    tab2 <- tab_base +
    geom_text(aes(x=1, label=total)) +
    ggtitle("total")

    lay <- matrix(c(1,1,1,1,1,1,2,3), nrow=1)
    grid.arrange(plot1, tab1, tab2, layout_matrix = lay)

    enter image description here

    关于ggplot2 - ggplot grobs 与 tableGrob 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40265494/

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