如何正确地映射数据/数组以获得不同的颜色? D3.js

时间:2019-06-05 19:31:06

标签: d3.js

我已经搜索并感到困惑。

我的图形有几个规则条和一个具有5个不同值的堆叠条。我希望它们都是不同的颜色,所以有7种不同的颜色。

首先,我只是尝试为每个条形放置一种颜色(而忽略堆叠的条形)。我正在使用V4。

var data = [
  {month: "june", a: 500, color: 'green'},
  {month: "july", a: 90, b: 90, c: 90, d: 90, e: 90, color: 'orange'},
  {month: "august", a: 240, color: 'red'}
];

var series = d3.stack()
    .keys(["a", "b", "c", "d", "e", "f", "g", "h", "color"])
    .offset(d3.stackOffsetDiverging)
    (data);

然后我要尝试以这种方式引用它。

.attr("fill", data.map(function(d) { return d.color; }))

显然这是错误的,因为我没有颜色。也尝试了其他一些东西。

对于堆叠的条形图(或全部三个),我确实是这样的,但我想对颜色进行硬编码,而不要根据值范围将其颜色显示。

d3.scale.ordinal().range(["hexcolor1", "hexcolor2", "hexcolor3", "hexcolor4", "hexcolor5"]).range()

发现此问题可以回答我的部分问题:Changing the colors of each of the Stacked Bar chart with different Color in D3

我的常规色条(我有一些未堆叠的色条)都获得了我的颜色阵列中的第一种颜色。我的堆叠条形图获得阵列中的不同颜色。

琴键链接已过期,但是OP提到“另一组颜色”吗?我不确定您的代码是否仅用于重复颜色。我想要类似的东西:红色条(未堆叠),绿色条(未堆叠),紫色/粉红色/黄色/橙色条,蓝色条(未堆叠)。

编辑:实际上,当我输入j代码时,我没有任何颜色(全黑)。

var data = [
  {month: "mike", a: 500},
  {month: "judy", a: 90, b: 90, c: 90, d: 90},
  {month: "matt", a: 240}
];

var mycolors = ['#386cb0','#487cc0','#589cd0','#988cf0'];

var mycolorsb = ['#FFFF00'];

var series = d3.stack()
    .keys(["a", "b", "c", "d", "e", "f", "g", "h", "color"])
    .offset(d3.stackOffsetDiverging)
    (data);

var svg = d3.select("svg"),
    margin = {top: 30, right: 20, bottom: 60, left: 130},
    width = +svg.attr("width"),
    height = +svg.attr("height");

var y = d3.scaleBand()
    .domain(data.map(function(d) { return d.month; }))
    .rangeRound([margin.top, height - margin.bottom])

var x = d3.scaleLinear()
    .domain([0,1000])
    .rangeRound([margin.left, width - margin.right]);

svg.append("g")
  .selectAll("g")
  .data(series)
  .enter().append("g")
    .attr ("fill", function(d, i, j) { return mycolors[(j*4)+i]; })
  .selectAll("rect")
  .data(function(d) { return d; })
  .enter().append("rect")
    .attr("height", 75)
    .attr("y", function(d) { return y(d.data.month); })
    .attr("x", function(d) { return x(d[0]); })
    .attr("width", function(d) { return x(d[1]) - x(d[0]); })

我也尝试执行以下代码: d3.js-adding different colors to one bar in stacked bar chart,但似乎不像我那样做。遮罩条在阵列中仍具有相同的第一色。

.attr("fill", function(d, i, j) { return d.month === "matt" ? mycolorsb[i] : mycolors[i]; })

创建颜色后,我可以替换/覆盖颜色,因为它只有2或3个非堆叠的条形。我不知道该怎么做。

0 个答案:

没有答案
相关问题