输出中带有图表的汇总表

时间:2020-12-21 15:46:38

标签: r function r-markdown

这是我想要的输出,我想要的输出是在单个输出中获得带有图表的汇总表 enter image description here


  T1 <- as.data.frame(table(data[[var]]))
  bar_chart <- barchart(data[[var]]))

1 个答案:

答案 0 :(得分:2)

enter image description here

我似乎无法重现您的示例,但我知道您想将表格和情节结合起来。我以一些假设数据为例。

您可以使用 grob 包中的 tableGrob 函数将表创建为 gridExtra 对象,使用 {{1} 将 ggplot 转换为 grob 对象} 来自 ggplotGrob 包,然后以不同的方式组合它们。

  1. 来自 ggplot2 包的 annotation_custom 函数: 在这里你可以伪造一个空的 ggplot 并将表格和绘图排列在空绘图的不同区域(见下面的代码示例)
ggplot2

您还可以将灵活表强制为栅格 # making the plot plot_df <- data.frame(x=LETTERS[1:5], y=1:5) plot <- ggplot(plot_df, aes(x, y))+ geom_col() # making the table table_df <- data.frame(x=LETTERS[1:10], y=1:10) tabl <- tableGrob(d = table_df) # making the feck plot that will contain the plot and the table feck_plot_df <- data.frame(x=0:1, y=0:1) p <- ggplot(feck_plot_df)+ geom_blank()+ annotation_custom(grob = tabl, xmin = -Inf, xmax = 0.1, ymin = 0.15, ymax = 0.9)+ annotation_custom(grob = ggplotGrob(plot), xmin = 0.1, xmax = 1, ymin = -Inf, ymax = 1) # saving the combined plot ggsave(plot = p, filename = 'combined_plot.png', device = 'png', dpi = 300, width = 7.04, height = 3.77) ,然后使用 flexible::as_raster 进行 grob 并在空的 ggplot 中排列内容。根据您的更新,下面尝试排列 3 个地块。

grid::rasterGrob
  1. gridExtra 包中基于网格的布局函数:在这里,您可能想尝试 grid.arrange、arrangeGrob 或 gtable_cbind。
tabl <- tab_std(data=df, var = "col1", Name_of_variable = "state")
chrt <- donut(df,"col1")

tabl <- tab_std(data=df, var = "col1", Name_of_variable = "state")
bplt <- single_bar(df,"col1", SORT = TRUE)

ggplot() + 
  theme_void()+
  annotation_custom(grid::rasterGrob(as_raster(tabl)), xmin=-Inf, xmax=0.5, ymin=0.5, ymax=Inf)+
  annotation_custom(ggplotGrob(chrt), xmin=-Inf, xmax=0.5, ymin=-Inf, ymax=0.5)+
  annotation_custom(ggplotGrob(bplt), xmin=0.5, xmax=Inf, ymin=-Inf, ymax=Inf)

一旦您将绘图保存在某处,您就可以使用 tabl <- tab_std(data=df, var = "col1", Name_of_variable = "state") chrt <- donut(df,"col1") tabl <- tab_std(data=df, var = "col1", Name_of_variable = "state") bplt <- single_bar(df,"col1", SORT = TRUE) grid.arrange(grid::rasterGrob(as_raster(tabl)), ggplotGrob(chrt), ggplotGrob(bplt), layout_matrix = cbind(rbind(1,2), rbind(3,3))) 包中的 include_graphics 函数将其包含到您的 rmarkdown 中。也可以不保存直接包含。

相关问题