【问题标题】:ggplot plots within a table表格内的ggplot图
【发布时间】:2021-04-09 03:07:49
【问题描述】:

问题

我想制作一个漂亮的表格,其中一列的单元格中有 ggplots。一个关键因素是我想最终创建该表的 pdf 输出。

到目前为止我已经尝试过什么

希望下面的例子是可以理解的。基本上我发现我可以使用 gt 包实现我想要的。问题是这会创建一个 html 小部件,然后您必须使用 phantomJS 和 webshot 将其导出为 pdf。

library(dplyr)
library(purrr)
library(gt)
library(ggplot2)


dat = tibble(
  RowLabel = letters[1:5],
  Numeric = seq(100,500,100)
) %>% 
  mutate(
    plotData = RowLabel %>% map(function(pos){
      tibble(y=runif(10)*100) %>% 
        arrange(desc(y)) %>% 
        mutate(x=row_number())
    }),
    plot_obj = plotData %>% map(function(df){
      df %>%
        ggplot(aes(x=x,y=y))+
        geom_col()
    }),
    plot_grob = plot_obj %>% map(cowplot::as_grob)
  )


tab = dat %>% 
  select(RowLabel, Numeric) %>% 
  mutate(
    ggplot = NA
  ) %>% 
  gt() %>% 
  text_transform(
    locations = cells_body(vars(ggplot)),
    fn = function(x) {
      dat$plot_obj %>%
        map(ggplot_image, height = px(50))
    }
  )
tab

我想要什么

我想要一个类似于上面例子的输出。但是,我想要一个不需要我使用 html 小部件并且可以直接保存为 pdf 而无需使用其他程序的解决方案。这可以使用ggplot吗?我已经开始了解更多关于 grids/grobs/gtables 等的知识,但还没有取得任何有意义的进展。

提前致谢!

【问题讨论】:

标签: r ggplot2 gt


【解决方案1】:

也许您可以调整gtsave() 函数以适应?例如

library(dplyr)
library(purrr)
library(gt)
library(ggplot2)


dat = tibble(
  RowLabel = letters[1:5],
  Numeric = seq(100,500,100)
) %>% 
  mutate(
    plotData = RowLabel %>% map(function(pos){
      tibble(y=runif(10)*100) %>% 
        arrange(desc(y)) %>% 
        mutate(x=row_number())
    }),
    plot_obj = plotData %>% map(function(df){
      df %>%
        ggplot(aes(x=x,y=y))+
        geom_col()
    }),
    plot_grob = plot_obj %>% map(cowplot::as_grob)
  )
tab = dat %>% 
  select(RowLabel, Numeric) %>% 
  mutate(
    ggplot = NA
  ) %>% 
  gt() %>% 
  text_transform(
    locations = cells_body(vars(ggplot)),
    fn = function(x) {
      dat$plot_obj %>%
        map(ggplot_image, height = px(50))
    }
  )
tab %>% 
  gt::gtsave(filename = "test.pdf", vwidth = 180, vheight = 250)

(R v4.0.3 / gt v0.2.2)

【讨论】:

  • 感谢您的回复。这个解决方案似乎基本上是我已经尝试过的。 gtsave 函数使用 webshot,而 webshot 又使用 phantomJS。但考虑到 Joel Kandiah 的评论,看来这种解决方案可能是唯一没有显着复杂性的方法。此外,我认为您没有从问题中复制粘贴整个代码 sn-p (不确定您是否可以编辑)。
猜你喜欢
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 2020-09-20
相关资源
最近更新 更多