rggplot2alpha-transparencyggpmisc

How to set alpha (=transparency) for a geom_table() table's text and/or background


What I'm trying to do is annotate a plot with the background of the table transparent. This gives no errors but doesn't seem to set the alpha correctly

library(ggplot2)
library(ggpmisc)

# Sample data for plotting
plot_data <- data.frame(
  x = runif(100),
  y = runif(100)
)

# Table data to display on the plot
table_data <- data.frame(
  Metric = c("Accuracy", "Precision", "Recall"),
  Value = c("0.95", "0.93", "0.92")
)

# Create the plot
ggplot(plot_data, aes(x = x, y = y)) +
  geom_point(size = 3,colour="black") +
  geom_table(
    data=data.frame(x=.1,y=.5),
    aes(x=x,y=y,label = list(table_data)),
    size=20,
    alpha = 0.5  # Adjusts background transparency
  ) +
  theme_minimal()

Perhaps I'm not understanding the documentation but it looks like alpha should be set this way: https://www.rdocumentation.org/packages/ggpmisc/versions/0.3.9/topics/geom_table

With 'ggpp' 0.5.9 released on 28-06-2025 the code above does work as expected. A bug affected earlier 'ggpp' versions.

I tried the example in the documentation where fill is set with an alpha variable appended (six-digit hexadecimal colour plus two-digit alpha setting) and that does work. But it doesn't let me use alternating shading for rows.

geom_table(data = df, aes(x = x, y = y, label = tb),
             color = "red", fill = "#FFCCCC", family = "serif", size = 5,
             angle = 90, vjust = 0)

Solution

  • After a look at the docs and the source code and some experimenting I have no clue how set the background opacity in geom_table without using a custom table theme, i.e. one option would be to use a customized table theme where besides the opacity I also added an example on how to set the (alternating) background fill colors:

    library(ggplot2)
    library(ggpmisc)
    
    set.seed(123)
    
    # Sample data for plotting
    plot_data <- data.frame(
      x = runif(100),
      y = runif(100)
    )
    
    # Table data to display on the plot
    table_data <- data.frame(
      Metric = c("Accuracy", "Precision", "Recall"),
      Value = c("0.95", "0.93", "0.92")
    )
    
    # ggpp::ttheme_gtdefault is the default used by geom_table
    ttheme <- ggpp::ttheme_gtdefault(
      base_size = 20 * .pt
    )
    ttheme$core$bg_params$alpha <- .6
    ttheme$core$bg_params$fill = c("red", "blue")
    
    # Create the plot
    ggplot(plot_data, aes(x = x, y = y)) +
      geom_point(size = 3, colour = "black") +
      geom_table(
        data = data.frame(x = .1, y = .5),
        aes(x = x, y = y, label = list(table_data)),
        table.theme = ttheme
      ) +
      theme_minimal()
    

    Created on 2025-06-16 with reprex v2.1.1