简体   繁体   中英

How to add name of column in column of rownames in tableGrob in R?

I am trying to create a chart from a matrix input in R. I am using tableGrob for this. My matrix is in such a way that rownames are YEAR ie 2000, 2001, .... This is the code that I am using right now.

tt1 <- ttheme_minimal(
core=list(bg_params = list(fill = "#ffffff", alpha = 1),
          fg_params=list(fontface="bold", hjust=0, x=0.05, fontsize=9, just='centre', 
                         col=ifelse(startsWith(matrix_input, "-"), "#FF0000", "#228B22")), 
          padding=unit.c(unit(10, "mm"), unit(2.5, "mm"))
),
colhead=list(fg_params=list(fontface='bold', col='#3c3c3c', hjust=0, x=0.05, fontsize=9)),
rowhead = list(fg_params=list(fontface='bold', col='#3c3c3c', hjust=0, x=0.05, fontsize=9), 
               padding=unit.c(unit(10, "mm"), unit(2.5, "mm")))
                    )
tGrob <- tableGrob(as.matrix(matrix_input), rows = rownames(matrix_input), theme = tt1)
tGrob <- add_border_at_bottom_of_row(1)
grid.arrange(tGrob)

In the output, the column name for rownames (2004, 2005....) is blank. I need to name it as 'Year'. Can someone please help and guide me how to do it?

You could either add the rownames as a new column in your data,

library(gridExtra)
grid.table(tibble::rownames_to_column(iris[1:4,1:2], 'title'), rows=NULL)

or keep them as rownames and manually add a title in the gtable cell. Styling might be easier if copying a textGrob from the existing table and just changing the text,

library(gridExtra)
library(grid)

tg <- tableGrob(iris[1:4,1:2])
tg <- gtable::gtable_add_grob(tg, textGrob('title', hjust=1,x=1), t=1,l=1, b=1,r=1,z=0)
tg$layout$clip <- 'off'
grid.newpage()
grid.draw(tg)


tg2 <- tableGrob(iris[1:4,1:2])
tg2 <- gtable::gtable_add_grob(tg2, editGrob(tg$grobs[[1]], label='new'), t=1,l=1, b=1,r=1,z=0)
tg2$layout$clip <- 'off'
grid.newpage()
grid.draw(tg2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM