Home > OS >  Colour rows by one factor in geom_table
Colour rows by one factor in geom_table

Time:05-19

I am trying to make a ggplot2 graph in which I have a "classic" dot plot together with a table. This is an example of the plot I am making:

library(dplyr)
library(tibble)
library(ggplot2)
library(ggpmisc)
mtcars[1:10,] %>%
  select(cyl, mpg, wt) -> tb

df <- tibble(x = 5.45, y = 34, tb = list(tb))

# using defaults
ggplot(mtcars, aes(wt, mpg, colour = factor(cyl)))  
  geom_point()  
  geom_table(data = df, aes(x = x, y = y, label = tb))

This is the output of the code: enter image description here

I would however the rows of the table be coloured according to the factor cyl. So every rows which has carb==4 is red, ==6 is green and ==8 is blue. I don't need the column cyl to appear in the table, so that can be removed (if possible). Is there a way to do it?

Thanks a lot in advance for your precious help, Luca

CodePudding user response:

Unlike most of the ggplot ecosystem, you can't just use a fill aesthetic inside geom_table, and instead need to create a table theme which gets passed to table.theme inside geom_table. This means it is somewhat inconvenient to achieve the desired effect, but it is possible with something like the following:

thm <- gridExtra::ttheme_default()
fills <- scales::hue_pal()(3)[as.numeric(factor(df$tb[[1]]$cyl))]
thm$core$bg_params$fill <- fills
df$tb[[1]] <- df$tb[[1]][-1]

ggplot(mtcars, aes(wt, mpg, colour = factor(cyl)))  
  geom_point()  
  geom_table(data = df, aes(x = x, y = y, label = tb), table.theme = thm)

enter image description here

CodePudding user response:

It is a bit hacky, but using the table.theme argument, you can supply the table with your own background colors (see Controlling the colors of rows in ggplot table annotation).

First, we construct a vector which contains a required background color for each row. Then, we use those colors in the table.theme argument of geom_table.

library(dplyr)
library(tibble)
library(ggplot2)
library(ggpmisc)
mtcars[1:10,] %>%
    select(cyl, mpg, wt) -> tb

df <- tibble(x = 5.45, y = 34, tb = list(tb))

# Construct vector of required background colors (from default ggplot2 theme)
colors <- scales::hue_pal()(n_distinct(tb$cyl))
colors <- colors[factor(tb$cyl)]

# using defaults
ggplot(mtcars, aes(wt, mpg, colour = factor(cyl), fill = factor(cyl)))  
    geom_point()  
    geom_table(data = df, aes(x = x, y = y, label = tb),
               table.theme = gridExtra::ttheme_default(core = list(bg_params=list(fill=colors))))
  • Related