Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

datagrid - R tableGrob heatmap or conditional formating in column

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.

enter image description here

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...