在 table 中更改栏的颜色和方向

Change bar's color and orientation in a table

如果数字为负数,我想更改条形的边和颜色。我目前正在使用此代码,但我不知道该怎么做。

为了更好地理解我想要什么,我希望值为负的 Orihuela 条为红色且在左侧。

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() 


欢迎来到 SO,@Oxford Bicho!

关注 获得了这个:

---
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() 
```

-输出