基于数字d3的比较的彩色分组条形图

时间:2017-06-07 17:33:54

标签: javascript d3.js

我正在建立一个分组的条形图。在图表中,我想以不同的方式为一组条形图着色,因为它的密苏里数大于全国平均数。但是,我的else if语句不适用于fill函数。任何人都可以告诉我,我应该怎样做才能根据数字的比较对图表进行不同的着色?在此先感谢!!

这是我的代码

<svg id="bodychart" width="900" height="500" style="display: block; margin: auto"></svg>

<script>

var svg = d3.select("#bodychart"),
    margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top +")" ); //Not quite understand (??)

var x0 = d3.scaleBand()
    .rangeRound([0, width])
    .paddingInner(0.1);

var x1 = d3.scaleBand()
    .padding(0.05);

var y = d3.scaleLinear()
    .rangeRound([height, 0]);

var z = d3.scaleOrdinal()
    .range(["#F63014", "#ABABAB"]);

var tooltip = d3.select("body").append("div").attr("class", "toolTip");

d3.csv("number.csv", function(d, i, columns){
  for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = + d[columns[i]];
    return d;
}, function(error, data) {
  if (error) throw error;

  var keys = data.columns.slice(1); 

  x0.domain(data.map(function(d) {return d.BodyParts; }));
  x1.domain(keys).rangeRound([0, x0.bandwidth()]);
  y.domain([0, d3.max(data, function(d) {return d3.max(keys, function(key) {return d[key]; }); })]);

  g.append("g")
    .selectAll("g")
    .data(data)
    .enter()
    .append("g")
      .attr("transform", function(d) {return "translate(" + x0(d.BodyParts) + ",0)"; })
    .selectAll("rect")
    .data(function(d) {return keys.map(function(key){return {key: key, value: d[key]}; }); })
    .enter()
    .append("rect")
      .attr("x", function(d) {return x1(d.key);})
      .attr("y", function(d) {return y(d.value);})
      .attr("width", x1.bandwidth())
      .attr("height", function(d){return height - y(d.value);})
      .attr("fill", function(d, i) {

        if (d.value['Missouri'] > d.value['National_Average']) {
          return z(d.key);
        } else (d.value['Missouri'] < d.value['National_Average']) {
          return "yellow";
        }
        })
      .on("mousemove", function(d){
        tooltip
          .style("left", d3.event.pageX - 50 + "px")
          .style("top", d3.event.pageY - 70 + "px")
          .style("display", "inline-block")

          .html("<span style='font-weight: bold'>"+ (d.key) +"</span>" + ":" + "<br>" + "$" + d3.format(",.0f")(d.value));

    })
        .on("mouseout", function(d){ tooltip.style("display", "none");});

    g.append("g")
      .attr("class", "axis")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x0));

    g.append("g")
        .attr("class", "axis")
        .call(d3.axisLeft(y).ticks(10, ",.0f"))
      .append("text")
        .attr("x", -32)
        .attr("y", y(y.ticks().pop()) + 0.5)
        .attr("dy", "-3em")
        .attr("fill", "#000")
        .attr("font-weight", "bold")
        .attr("text-anchor", "start")
        .text("Dollars");

});

这是我的csv文件:

    BodyParts,Missouri,National_Average
    Arm,115100,169878
    Leg,102697,153221
    Hand,86821,144930
    Thumb,29767,42432
    Index Finger,22325,24474
    Middle Finger,17364,20996
    Ring Finger,17364,14660
    Pinky,10915,11343
    Foot,74418,91779
    Big Toe,19845,23436
    Eye,69457,96700
    Ear,24310,38050
    Testicle,0,27678

1 个答案:

答案 0 :(得分:0)

由于每对的完整数据都在父选择中,因此您必须在进行任何比较之前获取它。

因此,在为每个栏设置填充时,这......

var parentData = d3.select(this.parentNode).data()[0];

...将存储该对的数据,即MissouriNational_Average

然后,使用该对象有条件地填充条形图。这是一种方法(当然,有更短的方法,但我相信这个冗长的片段更适合你):

.attr("fill", function(d, i) {
    var parentData = d3.select(this.parentNode).data()[0];
    if (d.key === "Missouri") {
        if (parentData.Missouri > parentData.National_Average) {
            return "green"
        } else {
            return "red"
        }
    } else {
        if (parentData.Missouri < parentData.National_Average) {
            return "green"
        } else {
            return "red"
        }
    }
})

这是一个显示它的plunker:http://plnkr.co/edit/dfjKFUpuiJvLs6wWkO99?p=preview