Align text in color_bar

Hi! I'm trying to modify the color_bar function from formattable.

I'm making this table but I want the text to be align to the right, if I add the align argument in the kable it moves the whole bar, and I just want to move the text.

mtcars %>% 
mutate(mpg = color_bar("lightblue")(mpg)) %>% 
kable("html", escape = F) %>% 
kable_styling("hover", full_width = T, bootstrap_options = "bordered") %>%
add_header_above(c("","values" = 11))

I tried this, add the text-align to the color_bar definition, but this moves the text to the end of the bar, not the end of the cell.

color_bar_text <- function (color = "lightgray", fun = "proportion", ...) 
{
  fun <- match.fun(fun)
  formatter("span", style = function(x) style(display = "inline-block", 
                                              direction = "ltr", `unicode-bidi` = "plaintext", `border-radius` = "4px",
                                              `text-align` = "right", `padding-right` = "2px", `background-color` = csscolor(color), 
                                              width = percent(fun(as.numeric(x), ...))))
} 

Do you have any idea of how can I get this:
color_bar

Thanks in advance.

Below is one approach that manually creates and styles the color bar and text separately, combining them via paste0(). In order to get both to fit in the column, I scaled the width of the bar (i.e. mpg_pct) by 0.7 and set the column width via column_spec().

mtcars |>
  mutate(mpg_pct = mpg/max(mpg)) |>
  mutate(mpg = paste0(
    # create and style the color bar (scaled to 0.7 width to fit the text)
    '<span style="display: inline-block; 
                  direction: rtl; unicode-bidi: 
                  plaintext; border-radius: 4px; 
                  padding-right: 2px; 
                  background-color: lightblue; 
                  width:', 100 * mpg_pct * .7, '%">&nbsp;</span>',
    # style the text
    '<span style="text-align: right">', sprintf("%.1f", round(mpg, 1)), '</span>')) |>
  select(-mpg_pct) |>
  kable("html", escape = F) %>% 
  kable_styling("hover", full_width = T, bootstrap_options = "bordered") %>%
  column_spec(2, width = '8em') |>
  add_header_above(c("","values" = 11))

image

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.