modifying the colors of a grid table

30 Views Asked by At

i have this dataframe (the gdp of a certain country and a subregion of said country, and the yearly changes in %). The dataframe is this:

Rows <- c("GDP state", "yearly change %", "GDP country", "yearly change %")


columns <- c("2012", "2013", "2014", "2015", "2016")


dataframe <- data.frame(data=list(c(5818, 6269, 6351, 6111, 6548), c("9.8%", "6.6%", "1.3%", "-3.8%", "7.1%"), c(182166, 189435, 190895, 179482, 200425), c("1.4%", "4%", "0.8%", "-6%", "11.7%")),
                       row.names=Rows,
                       names=columns)

What i want is to generate a table using grid, in R. What i have at this point is this:

table_grid<- tableGrob(dataframe, rows = c(rownames(dataframe), NULL), theme = ttheme_default(
  bg_params = list(fill = rep(NA)),  # Use NA for transparent background
  core = list(fg_params = list(hjust = 1, x = 0.9)),
  rowhead = list(fg_params = list(hjust = 0, x = 0)),
  base_size = 13
))

table_grid$vp <- viewport(gp = gpar(fontsize = 8))  
pushViewport(viewport(x = 0.23, y = 0.7, height = 0.3))
grid.draw(table_grid)

I want the first column to have a blue fill and the rest to be transparent, but i havent been able to (the fill = rep(NA) did nothing). Any help could be appreciated!

1

There are 1 best solutions below

0
stefan On

You have to move the bg_params to the respective list, i.e. core for the the table cells or rowhead for the rows. Wasn't sure what you mean by first column, so I show both options:

Rows <- c("GDP state", "yearly change %", "GDP country", "yearly change %")
columns <- c("2012", "2013", "2014", "2015", "2016")

dataframe <- data.frame(
  list(
    c(5818, 6269, 6351, 6111, 6548),
    c("9.8%", "6.6%", "1.3%", "-3.8%", "7.1%"),
    c(182166, 189435, 190895, 179482, 200425),
    c("1.4%", "4%", "0.8%", "-6%", "11.7%")
  )
)
rownames(dataframe) <- columns
colnames(dataframe) <- Rows

library(grid)
library(gridExtra)

table_grid <- tableGrob(dataframe,
  rows = c(rownames(dataframe), NULL),
  theme = ttheme_default(
    core = list(
      fg_params = list(hjust = 1, x = 0.9),
      bg_params = list(
        fill = rep(c(
          "blue",
          rep(NA, 4)
        ), each = 5)
      )
    ),
    rowhead = list(
      fg_params = list(hjust = 0, x = 0),
      bg_params = list(
        fill = c(
          NA, rep("red", 5)
        )
      )
    ),
    base_size = 13
  )
)

grid.newpage()
# table_grid$vp <- viewport(gp = gpar(fontsize = 8))
# pushViewport(viewport(x = 0.23, y = 0.7, height = 0.3))
grid.draw(table_grid)