R tableGrob 热图或列中的条件格式 [英] R tableGrob heatmap or conditional formating in column

查看:23
本文介绍了R tableGrob 热图或列中的条件格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法创建与 excel 的条件格式类似的效果 -> 色阶,以便在 grid.table/tablegrob 对象中显示表格?颜色指示器对于列中较低的值应该是红色的,对于较高的值应该是绿色的.需要该对象格式,以便表格可以与图表一起以网格格式呈现.

Is there a way to create a similar effect to excel's conditional formating -> color scales in order to present a table in grid.table/tablegrob object? The color indicator should be red for the lower values and green for the higher values in the column. That object format is needed so the table can be presented in grid format along with plots.

谢谢.

推荐答案

您可以在 tableGrob 中执行此操作.您创建一个颜色向量,然后将它们分配给单元格.

You can do this within tableGrob. You create a vector of colours, and then assign these to the cells.

所以使用克莱门斯回答中的数据:

So using the data from clemens's answer:

library(gridExtra)
library(grid)

# define colour vector
# change `vec` argument of `findInterval` to suit your cut-points
cols <- c("red" ,"orange", "green") [findInterval(my_data$Balance, c(-Inf, 1e4, 2e4, Inf))]
# or 
# https://stackoverflow.com/questions/34517031/red-amber-green-sequential-palette-for-treemap-in-r
cols <- colorRampPalette(c("red", "yellow", "green"))(nrow(my_data))[rank(my_data$Balance)]


# create tales individually for each column
# this make it easy to assign colours to rows
t1 <- tableGrob(my_data["Balance"], 
               theme=ttheme_default(
                      core=list(bg_params = list(fill=cols)),
                      colhead = list(bg_params=list(fill="white", col="grey90"))), 
                      rows = NULL)
t2 <- tableGrob(my_data["ID"], 
               theme=ttheme_default(
                      core=list(bg_params = list(fill="white", col="grey90")),
                      colhead = list(bg_params=list(fill="white", col="grey90"))),
                      rows = NULL)

# join tables
tab <- gtable_combine(t2, t1)
# grid.newpage() ; grid.draw(tab)



# if also want to add black border
# https://stackoverflow.com/questions/31506294/gtable-put-a-black-line-around-all-cells-in-the-table-body
library(gtable)
tab <- gtable::gtable_add_grob(tab, 
                             grobs = rectGrob(gp=gpar(fill=NA, lwd=2)), 
                             t = 1, b = nrow(tab), l = 1, r = ncol(tab))

grid.newpage() ; grid.draw(tab)

这篇关于R tableGrob 热图或列中的条件格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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