【问题标题】:How to get negative values plotted in reactable bar chart?如何在可反应的条形图中绘制负值?
【发布时间】:2021-09-26 06:19:57
【问题描述】:

让我的负面条形图出现在我的reactable 表中时遇到了一些困难。我在下面有示例代码,如您所见,绘制了我的正值,但没有绘制负值。我被困在我所缺少的东西上,所以任何帮助都将不胜感激。

谢谢。

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

【问题讨论】:

  • 我运行你的代码,它返回“(div中的错误(style = list(flex =“1 1 0”)):找不到函数“div”)”
  • 对不起,@PeaceWang。我忘了在上面的代码中添加“htmltools”包。

标签: r reactable


【解决方案1】:

宽度的值应该是正数。

width <- abs(value)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多