【发布时间】:2022-01-06 20:03:25
【问题描述】:
给定一个数据样本如下:
df <- structure(list(category = c("food", "food", "food", "food", "electronic product",
"electronic product", "electronic product", "electronic product"
), type = c("vegetable", "vegetable", "fruit", "fruit", "computer",
"computer", "other", "other"), variable = c("cabbage", "radish",
"apple", "pear", "monitor", "mouse", "camera", "calculator"),
price = c(6, 5, 3, 2.9, 2000, 10, 600, 35), quantity = c(2L,
4L, 5L, 10L, 1L, 3L, NA, 1L)), class = "data.frame", row.names = c(NA,
-8L))
我可以使用以下代码绘制表格图:
library(gt)
library(magrittr)
dt <- df %>%
group_by(category) %>%
gt() %>%
tab_header(
title = md("Category name")
)%>%
tab_style(
locations = cells_column_labels(columns = everything()),
style = list(
#Give a thick border below
cell_borders(sides = "bottom", weight = px(3)),
#Make text bold
cell_text(weight = "bold")
)
) %>%
tab_style(
locations = cells_row_groups(groups = everything()),
style = list(
cell_text(weight = "bold")
)
) %>%
cols_align(align = "center", columns = everything())
dt
gt::gtsave(dt, file = file.path("./Category_name.png"))
输出:
现在我希望循环 category 和 group_by(type) 为每个 category 生成多个图。同时,我还需要通过动态修改gtsave(dt, file = file.path("./Category_name.png")) 和tab_header(title = md("Category name"))%>% 来重命名每个plot 的名称为category。
我如何使用 R 和 gt 包来实现这一点?谢谢。
编辑:绘制食物类别
food <- df %>%
filter(category=='food') %>%
group_by(type) %>%
gt() %>%
tab_header(
title = md("Food")
)%>%
fmt_missing(
columns = where(is.numeric),
missing_text = "-"
) %>%
tab_style(
locations = cells_column_labels(columns = everything()),
style = list(
#Give a thick border below
cell_borders(sides = "bottom", weight = px(3)),
#Make text bold
cell_text(weight = "bold")
)
) %>%
tab_style(
locations = cells_row_groups(groups = everything()),
style = list(
cell_text(weight = "bold")
)
) %>%
cols_align(align = "center", columns = where(is.character)) %>%
cols_align(align = "right", columns = where(is.numeric))
gt::gtsave(food, file = file.path("./food.png"))
【问题讨论】: