Skip to content

Instantly share code, notes, and snippets.

@asbates
Created May 12, 2022 16:45
Show Gist options
  • Save asbates/bbc382c2f2ae54b5c319d44d2450afe8 to your computer and use it in GitHub Desktop.
Save asbates/bbc382c2f2ae54b5c319d44d2450afe8 to your computer and use it in GitHub Desktop.
Create a stacked bar chart in a reactable cell with css flexbox
library(reactable)
library(htmltools)
# https://thomaswilburn.github.io/viz-book/css-flex.html
# was crucual to figuring this out. thanks Thomas!
bar_chart <-
function(value,
color_left = "#78c2ad",
color_right = "#f3969a",
height = "16px"
) {
val_left <- paste0(value * 100, "%")
val_right <- paste0( (1 - value) * 100, "%")
bar_left <- div(
style = list(
background = color_left,
height = height
),
val_left
)
chart_left <- div(
style = list(
flexGrow = 1,
textAlign = "center",
flexBasis = val_left
),
bar_left
)
bar_right <- div(
style = list(
background = color_right,
height = height
),
val_right
)
chart_right <- div(
style = list(
flexGrow = 1,
textAlign= "center",
flexBasis = val_right
),
bar_right
)
div(
style = list(
display = "flex",
alignItems = "stretch"
),
chart_left,
chart_right
)
}
dat <- data.frame(val = c(.1, .2, .3))
reactable(
data = dat,
columns = list(
val = colDef(
name = "Stacked Bar Chart",
cell = function(value) { bar_chart(value) },
align = "center"
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment