Philipp Staudacher
Philipp Staudacher

Reputation: 175

How to write a superscript in the header of an R table?

I'm trying to get a superscript into the header of a table. The table will later be used as a label for a barplot. I therefore want to abbreviate some table titles and explain the abbreviations later in the graph legend.

I use the example provided earlier by Sathish

# libraries
library(gridExtra)   # for cool table
library(grid)        # for cool table

# create example
df <- data.frame( a = 1:6, b = rep( letters[1:3], each = 2 ) )

# Create plotmath superscript strings
df[1,1] = paste0(df[1,1],"^",1)              # i unsuccessfully tried to change the example
colnames(df)[1] <- expression('Title'^2)     # here another unsuccessful try

# Define theme to parse plotmath expressions
tt = ttheme_default(core=list(fg_params=list(parse=TRUE)))

tg_df <- tableGrob(d = df, theme=tt)

grid.newpage()
grid.draw(tg_df)

This gives me enter image description here

Thanks for your help.

Upvotes: 2

Views: 1628

Answers (1)

MrFlick
MrFlick

Reputation: 206197

There's an example of this in the tableGrob vignette. Just make sure to parse the column headers as well

tt <- ttheme_default(
  core = list(fg_params = list(parse=TRUE)), 
  colhead = list(fg_params = list(parse=TRUE))
)

tg_df <- tableGrob(d = df, theme=tt)

grid.newpage()
grid.draw(tg_df)

enter image description here

Upvotes: 3

Related Questions