Search code examples
rfontssizeformattable

How to change font size in a formattable table in R


I am using formattable package in R to make a KPI table with icons and conditional colors. I need to export the file as a png so I am not using it in the Rmarkdown environment.

I didn't find any information on formattable document to say how to change font size, some answers online explored changing font type by embedding the formattable code in html. However, due to my limitation of exporting as an image file, I would like to know if there's just a command I can put in the code to make the whole table fonts bigger.

KPI<-formattable(d, align='c',
list(A=formatter("span",style=x~ifelse(x>0,"green","red")))
)

Solution

  • You can use any CSS styles avaiable to "span" tag:

    library(formattable)
    
    
    conditional_font_size <- formatter(
        "span",
        style = x ~ ifelse(x > 5, "font-size:20px; color:red","font-size:10px; color:blue")
    )
    
    formattable(
        iris,
        list(
            Sepal.Length = conditional_font_size
        )
    )
    

    enter image description here

    To add CSS for headers:

    temp_file <- tempfile(fileext = ".html")
    table_html <- paste("<div><style>th{color:green;}</style>",as.character(ftable),"</div>")
    writeLines(table_html,temp_file)
    rstudioapi::viewer(temp_file)
    

    enter image description here