用与线条相同的颜色填充多折线图上的点

fill points on the multi-line chart with the same color as lines

本文关键字:填充 折线图 颜色      更新时间:2023-09-26

在条形图上,线条上的点是蓝色的(工作样本),尽管有一个函数可以用线条的颜色填充这些点

// circle points | кружочки на лініях
    point.selectAll("circle") 
    .data(function(d){ return d.values; })
    .enter().append("circle")
    .attr("cx", function(d) {
        return x(d.date) + x.rangeBand()/2;
      })
     .attr("cy", function(d, i) { return y(d.value); })
     .attr("r", 3)
     .style("fill", function(d) { return color(d.name); });

知道为什么它不起作用吗?

提前感谢!

调试

要调试这样的问题,请在设置fill属性的函数中使用console.log函数:

style("fill", function(d) { 
    console.log('d is', d)
    return color(d.name);
});

您将看到没有d.name。此属性未传递给point:

// circle points | кружочки на лініях
    point.selectAll("circle") 
    .data(function(d){ return d.values; }) // point has access to d.values, not to d.name.

解决方案

要解决此问题,您可以执行以下操作:

在值数组的每个项目中添加name属性

point.selectAll("circle")
  .data(function(d) {
    // add name inside each value inside `d.values`
    d.values.forEach(function(value) {
      value.name = d.name
    })
    return d.values;
  })

然后您的fill功能将正常工作。

修正了示例来说明解决方案。

根据最初的答案,您有不同的与圆圈相关的数据,它们是d.value而不是d.name
此外,您的颜色范围声明中缺少一个哈希符号:
var color = d3.scale.ordinal().range(["c9bebe", "#787676", "#4d4dff"]);,显然应表示为:
CCD_ 10。

我可以在所有这些讨论中补充的一件事是,为了简单明了,您可以直接将您的颜色与包含circles的组相关联。因此,您可以将样式添加到组中,而不是向circle元素添加样式:

var point = column.append("g")
  .attr({
    "class": "line-point",
    "fill": function(d) { return color(d.name); }
    });   

在代码的不同点上的console.log是一种很好的方法来发现问题。

JSFiddle调整