Customizing look of table inserted into a ggplot

85 Views Asked by At

I want to annotate a table to an existing ggplot with a specified theme. However, I'd like to adapt the look of the table and change the color of the gridlines and the background color of the table header. So far I managed to change the background color of the table but not other colors. How can this be modified.

Here a small working example:

# Creating a sample data frame
df <- data.frame(
  x = 1:10,
  y = rnorm(10)
)

# Creating a plot
p <- ggplot(df, aes(x, y)) +
  geom_point() +
  labs(title = "Scatter Plot Example", x = "X-axis", y = "Y-axis")+
  theme_bw()

# Creating a table legend
legend_table <- tibble(x = 5, y = 0,
                       tb = list(data.frame(  Category = c("A", "B", "C"),
                                              Value = c(10, 20, 30))))

# Adding a table as a legend using annotate
p + geom_table(data = legend_table,   aes(x = x, y = y, label = tb),
               color = "red", fill = "#FFCCCC",
               vjust = 1)
1

There are 1 best solutions below

0
Peter On

You can create your own table theme with gridExtra. Colours used are arbitrary for illustration.

library(ggplot2)
library(tibble)
library(ggpmisc)
library(gridExtra)

# Creating a sample data frame
df <- data.frame(
  x = 1:10,
  y = rnorm(10)
)

# Creating a plot
p <- ggplot(df, aes(x, y)) +
  geom_point() +
  labs(title = "Scatter Plot Example", x = "X-axis", y = "Y-axis")+
  theme_bw()

# Creating a table legend
legend_table <- tibble(x = 5, y = 0,
                       tb = list(data.frame(  Category = c("A", "B", "C"),
                                              Value = c(10, 20, 30))))

# create your own table theme based on `gridExtra::ttheme_default()`
# I had to look into the function to determine the arguments to adjust.

my_ttheme <- 
  gridExtra::ttheme_default(colhead = list(fg_params=list(col="white"),
                                           bg_params=list(fill="red")),
                            core = list(bg_params=list(fill = "#FFCCCC", col = "green")))

p + geom_table(data = legend_table,   aes(x = x, y = y, label = tb),
               vjust = 1,
               table.theme = my_ttheme)

Created on 2023-11-16 with reprex v2.0.2