【问题标题】:Using colors from JSON data in D3 Bullet Chart在 D3 子弹图中使用来自 JSON 数据的颜色
【发布时间】:2014-12-31 19:35:41
【问题描述】:

我是 d3js 的新手,在这里缺少一些基本的东西。

在我的 JSON 数据中,我添加了一个颜色元素 barColor(到第二组值):

[ {"title":"AMER Revenue","subtitle":"703 US$, in thousands","ranges":[840,945,1200],"measures":[703],"markers":[1050]}, {"title":"AMER COGS","subtitle":"587 US$, in thousands","ranges":[1200,832.5,740],"measures":[587],"markers":[925],"barColor":["red"]} ]

JSON barColor 数据被正确读取,因为我可以在各种上下文中使用它,但不是在我想要的地方。

这是我得到的(完整的其他成功的测试被注释掉了):

/* Select the bars and use the color from the json data */
  d3.selectAll(".bullet .measure.s0")
      //.style("fill", "red"); //This works. All .measure.s0 bars set to red.
      .style("fill", function(d) { return d.barColor; }); //Why doesn't this work?

具体来说,它是 d3.selectAll(".bullet .measure.s0").style("fill", function(d) { return d.barColor; }); t 以我期望的方式工作。也就是说,我希望 d.barColor 将 measure.s0 的填充更改为红色。

我花了很多时间阅读和搜索,但似乎卡住了。

提前感谢您的任何指导。

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    您不想在这种情况下使用.style。请改用.attr,因为barColor 已在JSON 数据中定义。

    要修复它,请尝试更改:

    .style("fill", function(d) { return d.barColor; });

    对此:

    .attr("style", function(d) { return d.barColor; });

    我本人对 d3 还有些陌生,因此您可能需要对其进行一些调整,但希望它能让您走上正确的轨道。

    【讨论】:

    • @user2679918 这对你有用吗?如果没有,请告诉我,我们可以解决更多问题。
    猜你喜欢
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2021-12-15
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多