首页 > 解决方案 > kableExtra 无法弄清楚如何添加 spec_plot

问题描述

我正在尝试将 spec_plot 添加到我的 kable 中。我的数据看起来像这样。

present_table = data.frame(country = c("Austria", "Belgium", "Bulgaria", "Cyprus"),
                          "2010" = c(140,136,128,76),
                          "2016" = c(118,125,156,54),
                          "2017" = c(101,145,105,50),
                          "2018" = c(67,123,90,NA))

我想添加一个带有折线图的列,它显示了从 2010 年到 2018 年的演变。我已经尝试了所有我可以在网上很好的方法,但我无法弄清楚......

卡布尔

knitr::kable(present_table, "latex", caption = title, booktabs = F,
             align = "ccccc") %>%
  kable_styling(position = "left",
                full_width = F, 
                font_size = 8) %>%
  column_spec(1:1, bold = T) %>%
  column_spec(1:2, border_left = F, border_right = F) %>%
  row_spec(0:0, bold = T, color = "white", background = ms_table_header) %>%
  row_spec(1, hline_after = F) %>% 
  row_spec(2, hline_after = F) 

有谁知道如何做到这一点?

提前谢谢了!

标签: kableextra

解决方案


按照https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf(第12-13页),您需要先整理数据以创建列表(检查ptmeltpt_list)。我不得不从你的代码中删除一些东西,因为你没有提供它。

你可以试试这个.Rmd文件:

---
title: "spec_plot"
output: pdf_document
---
  
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

```{r pt, message=FALSE, warning=FALSE}
library(kableExtra)
library(tidyverse)

present_table = data.frame(country = c("Austria", "Belgium", "Bulgaria", "Cyprus"),
                           "2010" = c(140,136,128,76),
                           "2016" = c(118,125,156,54),
                           "2017" = c(101,145,105,50),
                           "2018" = c(67,123,90,NA))
colnames(present_table) <- c("country", "2010", "2016", "2017", "2018")

library(reshape2)
ptmelt <- melt(present_table, id.vars = "country") %>%
  arrange(country)

pt_list <- split(ptmelt$value, ptmelt$country)

present_table %>%
  mutate(line1 = "") %>%
  kbl("latex", caption = "title", booktabs = F,
             align = "ccccc") %>%
  kable_styling(position = "left",
                full_width = F, 
                font_size = 8,
                latex_options = c("hold_position")) %>%
  column_spec(1:1, bold = T) %>%
  column_spec(1:2, border_left = F, border_right = F) %>%
  row_spec(0:0, bold = T, color = "white") %>%
  row_spec(1, hline_after = F) %>%
  row_spec(2, hline_after = F) %>%
  column_spec(6, image = spec_plot(pt_list, same_lim = TRUE))
```

输出:

在此处输入图像描述


推荐阅读