grid.table图:根据行值设置单元格背景色

时间:2018-08-21 21:50:09

标签: r

我正在使用grid.table()将数据框打印为图形。我想用每行中包含的颜色作为十六进制代码填充单元格。

下面是我正在处理的行的示例。

df    
1 "#FFB325" "#000000" "#FFFFFF" "#00080"  
2 "#000000" "#000080" "#FFB325" "#FFFFFF"

我尝试使用grid.table(as.color(df))打印图。 Grid.table给了我我想要的东西,除了没有颜色编码的单元格。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

如果要为每个单元格选择背景颜色,请定义颜色集,然后使用自定义主题应用它。

尝试这样的事情:

color_df <- data.frame(color = c("#FFB325", "#00EE00", "#FFFFFF", "#008080", 
                                 "#00EE00", "#008080", "#FFB325", "#FFFFFF"),
                       stringsAsFactors = FALSE)


my_table_theme <- ttheme_default(core=list(bg_params = list(fill = color_df$color, col=NA)))

grid.table(color_df, theme = my_table_theme)

enter image description here

要显示多个具有不同颜色的列,请为每个列创建一个单独的主题,然后将它们与grid.arrange()一起显示:

color_df <- data.frame(blues = c("#F7FBFF", "#DEEBF7", "#C6DBEF", "#9ECAE1", "#6BAED6", "#4292C6", 
                                 "#2171B5", "#084594"),
                       greens = c("#F7FCF5", "#E5F5E0", "#C7E9C0", "#A1D99B", "#74C476", "#41AB5D", 
                                  "#238B45", "#005A32"),
                       spectral = c("#D53E4F", "#F46D43", "#FDAE61", "#FEE08B", "#E6F598", "#ABDDA4", 
                                    "#66C2A5", "#3288BD"),
                       stringsAsFactors = FALSE)


table_theme_blues <- ttheme_default(core=list(bg_params = list(fill = color_df$blues, col=NA)))
table_theme_greens <- ttheme_default(core=list(bg_params = list(fill = color_df$greens, col=NA)))
table_theme_spectral <- ttheme_default(core=list(bg_params = list(fill = color_df$spectral, col=NA)))

grid.arrange(
    tableGrob(color_df["blues"], theme=table_theme_blues, rows = NULL),
    tableGrob(color_df["greens"], theme=table_theme_greens, rows = NULL),
    tableGrob(color_df["spectral"], theme=table_theme_spectral, rows = NULL),
    nrow=1)

enter image description here