d3.js Sankey 图:矩形填充颜色 [英] d3.js Sankey diagram: rectangles fill color

查看:47
本文介绍了d3.js Sankey 图:矩形填充颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在玩 d3.js Sankey 图.

这个例子(如上图)中,颜色是使用

定义的

var color = d3.scale.category20();

对于每个节点都有一个矩形,该矩形通过改变样式来填充:

.style("fill", function(d) {return d.color = color(d.name.replace(/.*/, ""));})

我正在寻找有关使用自定义颜色的建议.如果我只想使用 6 种颜色,但根据 .json 文件中的值选择节点矩形颜色.

例如,假设我想显示 NFL 球队的蛇形图表.每种颜色代表球队所在的分区.所以如果他们移动到不同的分区,颜色就会改变.每个季节都会创建节点.类似的东西.

所以可以运行

node.append("rect").attr("height", function(d) { return d.dy; }).attr("宽度", sankey.nodeWidth()).style(填充",功能(d){return d.color = color(d.name.replace(/.*/, ""));}).style("stroke", function(d) {返回 d3.rgb(d.color). 深色 (2);}).append("标题").text(function(d) { return d.name + "
" + format(d.value); });

使用基于 json 文件中的值的颜色?我只是在想一个 if 语句,但有没有更简单的方法?我可以在 json 中包含十六进制颜色代码吗?

解决方案

在这种情况下,听起来您希望在 JSON 中包含颜色.您可以以浏览器识别的任何方式包含它,例如作为名称(白色")或十六进制(#fff").请参阅 SVG 规范,了解支持的颜色规范的完整列表.>

So I am playing around with the d3.js Sankey diagram.

In this example (pictured above) color is defined using

var color = d3.scale.category20();

For each node there is a rectangle, and that rectangle is filled by altering the style:

.style("fill", function(d) {
    return d.color = color(d.name.replace(/ .*/, ""));
})

I'm looking for suggestions on using custom colors. If I wanted to use only say 6 colors, but have the node rectangle colors chosen based on a value in the .json file.

For example, lets say I wanted to show a snakey chart of teams in the NFL. The colours each represent which division the teams play in. So if they move to a different division, the color changes. And the nodes are created for every season. Something along those lines.

So is it possible to run the

node.append("rect")
    .attr("height", function(d) { return d.dy; })
    .attr("width", sankey.nodeWidth())
    .style("fill", function(d) {
        return d.color = color(d.name.replace(/ .*/, ""));
    })
    .style("stroke", function(d) {
        return d3.rgb(d.color).darker(2);
    })
   .append("title")
    .text(function(d) { return d.name + "
" + format(d.value); });

with the color based on a value in the json file? I am thinking just an if statement, but is there an easier way? Could I just include the hex color code in the json?

解决方案

Sounds like you want to include the colour in the JSON in this case. You can include it in any way that the browser recognises, e.g. as a name ("white") or hex ("#fff"). See the SVG spec for a full list of supported colour specifications.

这篇关于d3.js Sankey 图:矩形填充颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆