前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >全了!!表格可视化制作技巧大汇总~~

全了!!表格可视化制作技巧大汇总~~

作者头像
DataCharm
发布2021-08-25 10:28:21
1.5K0
发布2021-08-25 10:28:21
举报

今天小编就来汇总一下R中表格(Table) 绘制方法,让你的数据展示不再单一。这里主要包括单一表格绘制和可视化+表格 两个方面。虽然表格制作可能Excel更擅长,但考虑到连贯性等问题,这里这里还是觉得有必要介绍一下,具体内容如下:

  • R-单一表格绘制
  • R-可视化+表格的”混搭“

R-单一表格绘制

这一部分可能有很多优秀的第三方包可以制作,这里小编主要介绍3个优秀的表格制作包,分别为R-DT、R-gt和R-sjPlot,其他表格绘制工具小编也会在这一部分结尾处汇总。

R-DT交互式表格制作

R-DT包可生成交互式HTML表格,这里小编举几个例子,如下:

「样例一」:

代码语言:javascript
复制
library(DT)
datatable(iris)

Example01 Of DT::datatable()

「样例二」:定制表格

代码语言:javascript
复制
# 定制表格
datatable(iris) %>% 
  formatStyle('Sepal.Length', fontWeight = styleInterval(5, c('normal', 'bold'))) %>%
  formatStyle(
    'Sepal.Width',
    color = styleInterval(c(3.4, 3.8), c('white', 'blue', 'red')),
    backgroundColor = styleInterval(3.4, c('gray', 'yellow'))
  ) %>%
  formatStyle(
    'Petal.Length',
    background = styleColorBar(iris$Petal.Length, 'steelblue'),
    backgroundSize = '100% 90%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'center'
  ) %>%
  formatStyle(
    'Species',
    transform = 'rotateX(45deg) rotateY(20deg) rotateZ(30deg)',
    backgroundColor = styleEqual(
      unique(iris$Species), c('lightblue', 'lightgreen', 'lightpink')
    ))

Example02 Of DT::datatable()

更多其他案例大家可参考:R-DT官网[1]

R-gt出版级别表格制作

首先,我们看一下gt绘制表格的主要参数,如下图(由于较为简单,这里直接给出英文原图):

Parts Of a gt Table

「样例一」:

代码语言:javascript
复制
library(gt)
library(tidyverse)
library(glue)

# Define the start and end dates for the data range
start_date <- "2010-06-07"
end_date <- "2010-06-14"

# Create a gt table based on preprocessed
# `sp500` table data
sp500 %>%
  filter(date >= start_date & date <= end_date) %>%
  select(-adj_close) %>%
  gt() %>%
  tab_header(
    title = "S&P 500",
    subtitle = glue::glue("{start_date} to {end_date}")
  ) %>%
  fmt_date(
    columns = date,
    date_style = 3
  ) %>%
  fmt_currency(
    columns = c(open, high, low, close),
    currency = "USD"
  ) %>%
  fmt_number(
    columns = volume,
    suffixing = TRUE
  )

Example Of gt table make

更多其他案例大家可参考:R-gt官网[2]

R-sjPlot回归模型表格制作

R-sjPlot包之前有介绍过其绘制图表能力(),小编着重介绍其绘制表格的能力。

「注意」:其绘制的表格结果都是回归模型的结果。案例如下:

「样例一」:regression results table

代码语言:javascript
复制
library(sjPlot)
library(sjmisc)
library(sjlabelled)

# sample data
data("efc")
efc <- as_factor(efc, c161sex, c172code)

m1 <- lm(barthtot ~ c160age + c12hour + c161sex + c172code, data = efc)
tab_model(m1)

Example Of sjPlot::tab_model()

「样例二」:定制化绘制

代码语言:javascript
复制
tab_model(
  m1,
  CSS = list(
    css.depvarhead = 'color: red;',
    css.centeralign = 'text-align: left;', 
    css.firsttablecol = 'font-weight: bold;', 
    css.summary = 'color: blue;'
  )
)

Example Of sjPlot::tab_model(CSS=**)

更多其他案例大家可参考:R-sjPlot回归表格绘制[3]

当然,除了上面介绍的外,下面小编再汇总列出其他的优秀第三方R包,小伙伴们可自行选择学习哈~如下:

  • R-gtsummary
  • R-kableExtra
  • R-formattable
  • R-reactable
  • R-flextable

R-可视化+表格的”混搭“

这一部分小编主要介绍如何在可视化绘制(ggplot2体系) 中添加表格内容,用以更加生动的展现数据价值。这里主要介绍R-ggpubr包和R-ggpmisc包。内容如下:

ggpubr

R-ggpubr包之前的推文(统计绘图 | 一行代码教你绘制顶级期刊要求配图)也介绍其绘制科研图表的方便些,这次的推文则重点介绍其绘制表格的函数,当然还是可以和ggplot2图表对象一起展示的。如下:

「样例一」:

代码语言:javascript
复制
library(ggpubr)
df <- head(iris)

# Default table
# Remove row names using rows = NULL
ggtexttable(df, rows = NULL)

Example Of ggpubr::ggtexttable()

「样例二」:ttheme("mBlue")

代码语言:javascript
复制
ggtexttable(df, rows = NULL, theme = ttheme("mBlue"))

Example Of ggpubr::ggtexttable(theme = ttheme("mBlue"))

「样例三」:定义自己需要的表格

代码语言:javascript
复制
ggtexttable(df, rows = NULL,
           theme = ttheme(
             colnames.style = colnames_style(color = "white", fill = "#8cc257"),
             tbody.style = tbody_style(color = "black", fill = c("#e8f3de", "#d3e8bb"))
           )
)

Example Of ggpubr::ggtexttable() make table you want

更多其他案例大家可参考:R-ggpubr表格绘制[4]

ggpmisc

R-ggpmisc包中绘制表格的函数为stat_fit_tb(),其功能主要是一些统计结果和拟合结果进行表格展示,当然你也可以看下之前介绍的推文(统计绘图 | 一行代码教你绘制顶级期刊要求配图)。如下:

「样例一」:

代码语言:javascript
复制
library(ggpmisc)
library(ggrepel)
library(xts)
library(lubridate)
library(nlme)
library(quantreg)
library(broom)
library(broom.mixed)
set.seed(4321)
# generate artificial data
x <- 1:100
y <- (x + x^2 + x^3) + rnorm(length(x), mean = 0, sd = mean(x^3) / 4)
my.data <- data.frame(x, 
                      y, 
                      group = c("A", "B"), 
                      y2 = y * c(0.5,2),
                      block = c("a", "a", "b", "b"),
                      wt = sqrt(x))

可视化绘制:

代码语言:javascript
复制
formula <- y ~ x + I(x^2) + I(x^3)
plot04 <- ggplot(my.data, aes(x, y)) +
  geom_point(shape=21,fill="#BC3C28",colour="black",size=3) +
  geom_smooth(method = "lm", formula = formula) +
  stat_fit_tb(method = "lm",
              method.args = list(formula = formula),
              tb.vars = c(Parameter = "term", 
                          Estimate = "estimate", 
                          "s.e." = "std.error", 
                          "italic(t)" = "statistic", 
                          "italic(P)" = "p.value"),
              label.y = "top", label.x = "left",
              parse = TRUE) +
 labs(
    title = "Example of <span style='color:#D20F26'>ggpmisc::stat_fit_tb function</span>",
    subtitle = "processed charts with <span style='color:#1A73E8'>stat_fit_tb()</span>",
    caption = "Visualization by <span style='color:#0057FF'>DataCharm</span>") +
  hrbrthemes::theme_ipsum(base_family = "Roboto Condensed")  +
  theme(
    plot.title = element_markdown(hjust = 0.5,vjust = .5,color = "black",
                                  size = 20, margin = margin(t = 1, b = 12)),
    plot.subtitle = element_markdown(hjust = 0,vjust = .5,size=15),
    plot.caption = element_markdown(face = 'bold',size = 12)
      )

Example01 Of ggpmisc::stat_fit_tb()

「样例二」:

代码语言:javascript
复制
ggplot(chickwts, aes(factor(feed), weight)) +
  stat_summary(fun.data = "mean_se") +
  stat_fit_tb(tb.type = "fit.anova", label.x = "left", size = 3) +
  scale_x_discrete(expand = expansion(mult = c(0.2, 0.5))) +
  coord_flip() +
   labs(
    title = "Example of <span style='color:#D20F26'>ggpmisc::stat_fit_tb function</span>",
    subtitle = "processed charts with <span style='color:#1A73E8'>stat_fit_tb()</span>",
    caption = "Visualization by <span style='color:#0057FF'>DataCharm</span>") +
  hrbrthemes::theme_ipsum(base_family = "Roboto Condensed")  +
  theme(
    plot.title = element_markdown(hjust = 0.5,vjust = .5,color = "black",
                                  size = 20, margin = margin(t = 1, b = 12)),
    plot.subtitle = element_markdown(hjust = 0,vjust = .5,size=15),
    plot.caption = element_markdown(face = 'bold',size = 12)
      )

Example02 Of ggpmisc::stat_fit_tb()

更多其他案例大家可参考:R-ggpmisc表格绘制[5]

总结

这篇推文小编几乎汇总了R中所有关于表格(table)制作的所有方法,包括单独绘制以及和ggplot2对象一起组合的表格绘制,可能还有好多优秀的包没有介绍到哈~,希望可以给大家带来些许帮助哈~

参考资料

[1]

R-DT官网: https://rstudio.github.io/DT/。

[2]

R-gt官网: https://gt.rstudio.com/index.html。

[3]

R-sjPlot回归表格绘制: https://strengejacke.github.io/sjPlot/index.html。

[4]

R-ggpubr表格绘制: https://rpkgs.datanovia.com/ggpubr/reference/ggtexttable.html。

[5]

R-ggpmisc表格绘制: https://docs.r4photobiology.info/ggpmisc/reference/stat_fit_tb.html。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-08-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DataCharm 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • R-单一表格绘制
    • R-DT交互式表格制作
      • R-gt出版级别表格制作
        • R-sjPlot回归模型表格制作
        • R-可视化+表格的”混搭“
          • ggpubr
            • ggpmisc
            • 总结
              • 参考资料
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档