Uneven alignment in R formattable in combination with kableExtra

759 Views Asked by At

I'm failing to get left aligned numbers in kableExtra in combination with formattable's barplots in table cells.

Code to reproduce in rmarkdown format:


title: "Untitled" output: html_document

knitr::opts_chunk$set(echo = TRUE)

library("formattable")
library("kableExtra")

Example

summary(cars)
cars$speed <- cars$speed * 100

Get a nice table

The table's first column is filled with tiny bar plots. All code is written following http://haozhu233.github.io/kableExtra/awesome_table_in_html.html manual of kableExtra.

plot.table <- cars
# need to modify the first few values to make sure the effect is visible.
plot.table$speed[1] <- 3
plot.table$speed[2] <- 25
plot.table$speed[3] <- 100

plot.table$speed <- color_bar("lightgreen")(plot.table$speed)

kbl(x = plot.table,
    escape = F) %>%
  kable_styling(bootstrap_options = c("striped", "hover"), fixed_thead = T)

The first three rows show values that are small in comparison to the rest of the values in the table. This makes theirs bars short and results in weirdly aligned numbers. The alignment is done according to the rightmost end of the green bar.

Inspecting the respective html element (e.g. FireFox "Inspect Element") reveals that the element "direction" is "rtl", which seems to be the default in kableExtra. Manually modifying the value of this parameter to "ltr" yields nicely left aligned values extending across the bar's end.

Table with barplot formatting

Unfortunately, I couldn't find the parameter in color_bar to modify this behaviour.

Any help pointing me to a way to get the values left aligned would be highly appreciated.

1

There are 1 best solutions below

0
On

as @juljo mentioned one obviously needs to modify the respective function. The body of the function could be copied out of the package contents.

f.color_bar <- function (color = "lightgray", fun = "proportion", ...) 
{
    fun <- match.fun(fun)
    formattable::formatter("span", style = function(x) style(display = "inline-block", 
        direction = "ltr", `border-radius` = "4px", 
        `padding-right` = "2px", `background-color` = csscolor(color), 
        width = percent(fun(as.numeric(x), ...))))
}

This hard coded the left to right behaviour, but isn't variable here as well.