gpt4 book ai didi

r - 用 R 绘制表格

转载 作者:行者123 更新时间:2023-12-02 00:14:01 25 4
gpt4 key购买 nike

我有以下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 结尾的列定义。

这就是 df 的图形应有的样子。

enter image description here

最佳答案

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

enter image description here

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 - 用 R 绘制表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32708192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com