I'm having some difficulty getting my negative bar chart to appear in my reactable
table. I have example code below and as you'll see, my positive values are plotted, but not my negative ones. I'm stuck on what I'm missing, so any help will be greatly appreciated.
Thanks.
library(tidyverse)
library(htmltools)
library(reactable)
bar_chart_pos_neg <- function(label, value, height = "16px",
pos_fill = "green", neg_fill = "red") {
pos_chart <- div(style = list(flex = "1 1 0"))
neg_chart <- div(style = list(flex = "1 1 0"))
width <- value
if (value < 0) {
bar <- div(style = list(marginLeft = "8px", background = neg_fill, width = width, height = height))
chart <- div(style = list(display = "flex", alignItems = "center", justifyContent = "flex-end"), label, bar)
neg_chart <- tagAppendChild(neg_chart, chart)
} else {
bar <- div(style = list(marginRight = "8px", background = pos_fill, width = width, height = height))
chart <- div(style = list(display = "flex", alignItems = "center"), bar, label)
pos_chart <- tagAppendChild(pos_chart, chart)
}
div(style = list(display = "flex"), neg_chart, pos_chart)
}
data <- data.frame(
Spread = c(3.8741435, -10.7573310, 6.8234219, 10.1194614, 3.6772631,
-4.2870001, 4.9933226, 2.6914581, -7.0133144, 4.9004934,
-8.6499655, -1.4826557, -0.2060462, 0.3289249, -2.1613399,
-4.5594886)
)
reactable(data, bordered = TRUE, columns = list(
Spread = colDef(
name = "Spread",
cell = function(value) {
label <- paste0(round(value), " pts")
bar_chart_pos_neg(label, value)
},
align = "center",
minWidth = 400
)
))
The value for width should be positive.
width <- abs(value)