Search code examples
rkablekableextraformattable

Change bar's color and orientation in a table


I'd like to change side and color of the bar if the number is negative. I was currently using this code but I don't know how to do it.

To better understand what I want, I'd like that Orihuela's bar, whose value is negative, to be red and to the left.

increasepob3<-structure(list(CP = c("03009 ", "03014 ", "03031 ", "03065 ", 
"03066 ", "03099 ", "03122 ", "03133 ", "12040 ", "12135 ", "46131 ", 
"46190 ", "46220 ", "46244 ", "46250 "), Municipio = c(" Alcoi", 
" Alacant", " Benidorm", " Elx", " Elda", " Orihuela", " Sant Vicent del Raspeig", 
" Torrevieja", " Castelló de la Plana", " Vila-real", " Gandia", 
" Paterna", " Sagunt", " Torrent", " València"), Evolución = c(0.18, 
3.88, 5.35, 3.54, 0.3, -6.23, 3.82, -11.35, 1.74, 1.79, 1.84, 
4.59, 2.6, 4.69, 1.28)), row.names = c(NA, -15L), class = "data.frame")

increasepob3$Evolución<- color_bar("lightgreen")(increasepob3$Evolución)

kbl(increasepob3, escape =F, digits = 2) %>%
  kable_paper() 


PLOT


Solution

  • Welcome to SO, @Oxford Bicho!

    Followed this answer to obtain this:

    ---
    title: "Use ifelse"
    author: "bttomio"
    date: "5/9/2021"
    output: html_document
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    library(kableExtra)
    library(formattable)
    library(tidyverse)
    ```
    
    ## R Markdown
    
    ```{r kable}
    increasepob3<-structure(list(CP = c("03009 ", "03014 ", "03031 ", "03065 ", 
    "03066 ", "03099 ", "03122 ", "03133 ", "12040 ", "12135 ", "46131 ", 
    "46190 ", "46220 ", "46244 ", "46250 "), Municipio = c(" Alcoi", 
    " Alacant", " Benidorm", " Elx", " Elda", " Orihuela", " Sant Vicent del Raspeig", 
    " Torrevieja", " Castelló de la Plana", " Vila-real", " Gandia", 
    " Paterna", " Sagunt", " Torrent", " València"), Evolución = c(0.18, 
    3.88, 5.35, 3.54, 0.3, -6.23, 3.82, -11.35, 1.74, 1.79, 1.84, 
    4.59, 2.6, 4.69, 1.28)), row.names = c(NA, -15L), class = "data.frame")
    
    cb <- function(x) {
      range <- max(abs(x))
      width <- round(abs(x / range * 50), 2)
      ifelse(
        x > 0,
        paste0(
          '<span style="display: inline-block; border-radius: 2px; ', 
          'padding-right: 2px; background-color: lightgreen; width: ', 
          width, '%; margin-left: 50%; text-align: left;">', x, '</span>'
        ),
        paste0(
          '<span style="display: inline-block; border-radius: 2px; ', 
          'padding-right: 2px; background-color: lightpink; width: ', 
          width, '%; margin-right: 50%; text-align: right; float: right; ">', x, '</span>'
        )
      )
    }
    
    increasepob3 %>%
      mutate(
        Evolución = cb(Evolución)
      ) %>%
      kbl(escape =F, digits = 2) %>%
      kable_paper() 
    ```
    

    -output enter image description here