繁体   English   中英

自动为堆叠的条形图进行颜色选择

[英]automate color pick for the stacked bar plots

以下是我尝试实现的示例jsfiddle。

http://jsfiddle.net/mwvhhe3o/

  1. 如何通过颜色范围而不是手动输入十六进制代码?

我尝试将颜色值传递为

var colorRange = d3.scale.category20();
 var colors = d3.scale.ordinal()
            .range(colorRange.range());

然后是.attr("fill", colorRange ); 分别填充 但是,没有成功。

  1. 我将图例值作为变量传递,有没有办法自动执行大小写转换? 案例切换的任何其他方法。

我的图例名称太多,无法手动命名。 下面的例子

 legend.append("text")
       .attr("x", width + 5)
       .attr("y", 9)
       .attr("dy", ".35em")
       .style("text-anchor", "start")
       .text(function(d, i) { 
        switch (i) {
        case 0: return "Anjou pears";
        case 1: return "Naval oranges";
        case 2: return "McIntosh apples";
        case 3: return "Red Delicious apples";
        case 4: return "cherries";
        case 5: return "plum";
        case 6: return "grapes";
        case 7: return "melons";
       }
    }); 

任何实现上述任务的方向或建议都是有帮助的

http://jsfiddle.net/ve38098w/

您需要做的就是创建一个新的色标

var colors = d3.scale.category20()

将每个图层点与一个水果相关联

var keys = ["redDelicious", "mcintosh", "oranges", "pears", "cherries", "plum","grapes", "melons"]

var dataset = d3.layout.stack()(keys.map(function(fruit) {
  return data.map(function(d) {
    return {x: parse(d.year), y: +d[fruit], name: fruit};
  });
}));

然后在数据连接期间开始传递水果名称。

var rect = groups.selectAll("rect")
  .data(function(d) { return d; })
  .enter()
  .append("rect")
  ...
  .style("fill", d=> colors(d.name))

var randomColor = colors('apple')这样的"apple"首次传递时,Apple将被分配一种颜色。 下次传递苹果时,将检索相同的颜色。

对于图例,使用前面讨论的色标进行数据连接以创建矩形。

var legend = svg.selectAll(".legend")
  .data(keys)
  .enter().append("g")
  .attr("class", "legend")
  .attr("transform", function(d, i) { return "translate(30," + i * 19 + ")"; });

legend.append("rect")
  .attr("x", width - 18)
  .attr("width", 18)
  .attr("height", 18)
  .style("fill", d=>colors(d));

legend.append("text")
  .attr("x", width + 5)
  .attr("y", 9)
  .attr("dy", ".35em")
  .style("text-anchor", "start")
  .text(d=>d);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM