用 R 绘制表格 [英] Plot a table with R

查看:91
本文介绍了用 R 绘制表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 data.frame:

df <- data.frame(id = c("a","b","c","d"),
                 s1.pch = c(NA,5,5,5),
                 s1.col = c(NA,"red","green","yellow"),
                 s2.pch = c(3,3,3,3),
                 s2.col = c("blue","red","green","yellow"),
                 s3.pch = c(1,1,NA,1),
                 s4.col = c("blue","red",NA,"yellow"))
# df
#
#   id s1.pch s1.col s2.pch s2.col s3.pch s4.col
# 1  a     NA   <NA>      3   blue      1   blue
# 2  b      5    red      3    red      1    red
# 3  c      5  green      3  green     NA   <NA>
# 4  d      5 yellow      3 yellow      1 yellow

我想把它绘制成一个表格,其中行名是 df$id,列名是 df 列中的 s1、s2、s3 前缀名称.表格的元素是彩色形状,其中形状由以 pch 结尾的列中的 pch 值定义,颜色由以 col 结尾的列定义.

I want to plot it as a table, where row names are df$id and the column names are the s1, s2, s3 prefixes in df's column names. The elements of the table are colored shapes where the shape is defined by the pch value in the columns ending with pch and the colors are defined by the columns ending with col.

对于df,这个图应该是这样的.

This is what the figure should like for df.

推荐答案

你可以组合参数并为 gridExtra::tableGrob 中的单元格定义一个自定义函数(我认为它只适用于开发版本)

you could combine the parameters and define a custom function for the cells in gridExtra::tableGrob (I think it only works in the dev version)

library(grid)
# devtools::install_github('baptiste/gridextra')
library(gridExtra)
df <- data.frame(id = c("a","b","c","d"), 
                 s1.pch = c(NA,5,5,5), 
                 s1.col = c(NA,"red","green","yellow"), 
                 s2.pch = c(3,3,3,3), 
                 s2.col = c("blue","red","green","yellow"), 
                 s3.pch = c(1,1,NA,1), 
                 s3.col = c("blue","red",NA,"yellow"))

d <- data.frame(id=df$id, 
                s1 = paste(df$s1.col, df$s1.pch, sep=","),
                s2 = paste(df$s2.col, df$s2.pch, sep=","),
                s3 = paste(df$s3.col, df$s3.pch, sep=","))


my_fun <- function(label, ...){

  s <- strsplit(label, ",")[[1]]
  col <- s[1]
  pch <- ifelse(s[2]=="NA", NA, as.numeric(s[2]))

  pointsGrob(0.5,0.5,pch=pch, gp=gpar(col=col, lwd=3, cex=0.5))
}

tt <- ttheme_minimal(12, core=list(fg_fun = my_fun), 
                     rowhead=list(fg_params=list(fontface="bold")))

grid.newpage()
grid.table(d[,-1], rows=levels(d[,1]), theme = tt)

这篇关于用 R 绘制表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆