如何使用d3.js设置图例以及如何为多线图设置不同的颜色?

时间:2016-05-10 10:48:12

标签: d3.js

<style> /* set the CSS */
  
  .chart2 {
    font: 12px Arial;
  }
  
  path {
    stroke: steelblue;
    stroke-width: 2;
    fill: none;
  }
  
  .axis path,
  .axis line {
    fill: none;
    stroke: #808080;
    stroke-width: 1;
    shape-rendering: crispEdges;
  }
  circle{
    fill: blue;
  }
  .tick line{
    opacity: 0.2;
  }
  .domain{
    display:none;
  }
</style>
  <script src="d3.min.js"></script>
  <script>
    // Set the dimensions of the canvas / graph
    var margin = {
        top: 30,
        right: 120,
        bottom: 30,
        left: 50
      },
      width = 600 - margin.left - margin.right,
      height = 270 - margin.top - margin.bottom;

    var parseDate = d3.time.format("%Y-%m-%d").parse;
    //2015-06-20
    // Set the ranges
    var x = d3.time.scale().range([0, width]);
    var y = d3.scale.linear().range([height, 0]);

    // Define the axes
    var xAxis = d3.svg.axis().scale(x)
      .orient("bottom").ticks(5);

    var yAxis = d3.svg.axis().scale(y)
      .orient("left").ticks(5).innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(10);;

    // Define the line 
    var priceline = d3.svg.line().interpolate("basis")
      .x(function(d) {
        console.log(d.T1);
        return x(d.T1);
      })
      .y(function(d) {
        return y(d.NATURE_QUERY);
      });

    // Adds the svg canvas
    var svg = d3.select(".chart2")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

    

    // Get the data
    d3.csv("datahere2.csv", function(error, data) {
      data.forEach(function(d) {
        console.log(d.T1);
        d.T1 = parseDate(d.T1);
      });
      // Scale the range of the data
      x.domain(d3.extent(data, function(d) {
        return d.T1;
      }));
      y.domain([0, d3.max(data, function(d) {
        return d.NATURE_QUERY;
      })]);

      // Nest the entries by symbol
      var dataNest = d3.nest()
        .key(function(d) {
          return d.CLOSING_DEPT;
        })
        .entries(data);
      console.log(dataNest);

      // Loop through each symbol / key
      dataNest.forEach(function(d) {
        svg.append("path")
          .attr("class", "line")
          .attr("d", priceline(d.values));
      });
      
      dataNest.forEach(function(d){
        var k = d.values
        var last = k[k.length -1];
        svg.append("circle")
        .attr("cx", function(d){return x(last.T1);})
        .attr("cy", function(d){return y(last.NATURE_QUERY);})
        .attr("r", 4);
        console.log(last)
        svg.append("text")
        .attr("x", function(){return x(last.T1) + 20;})
        .attr("y", function(){return y(last.NATURE_QUERY);})
        .text(function(){return last.NATURE_QUERY;})        
      })
      // Add the X Axis
      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

      // Add the Y Axis
      svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

    });
  </script>
大家好,我是D3.js的新手,所以有点难以理解这个概念。 帮我设置图表上方的图例,每一行应该是不同的颜色,根据该颜色,图例也应该来......并且图例应该是colomn名称为“CLOSING_DEPT”

1 个答案:

答案 0 :(得分:0)

将此添加到您的代码中:

var uniqueNames = [];
            data.forEach(function(d) {
              uniqueNames.push(d3.keys(d).filter(function(key) {
                  return key !== "NATURE_QUERY" /*&& key !== "exclude everything except CLOSING_DEPT "*/;
                }));
              });
            uniqueNames = d3.set(d3.merge(uniqueNames)).values();

var legend = svg.selectAll(".legend")
                .data(uniqueNames.sort())
                .enter().append("g")
                .attr("class", "legend")
                .attr("transform", function(d, i) {
                  return "translate(0," + i * 20 + ")";
                });

              legend.append("rect")
                .attr("x", width - 18)
                .attr("width", 18)
                .attr("height", 4)
                .style("fill", function(d) {
                  return color(d);
                });

              legend.append("text")
                .attr("x", width - 24)
                .attr("y", 6)
                .attr("dy", ".35em")
                .style("text-anchor", "end")
                .text(function(d) {
                  return d;
                });

//uniqueNames is the filtered name unique set of each of the line in multiline chart(in your case CLOSING_DEPT).

对于多线的多色油:

svg.append("path")
          .attr("class", "line")
          .attr("d", priceline(d.values)) .style("stroke", function(d) {
                  return color(d.name);
                });

以上是上述代码的example。根据您的要求更改数据和过滤逻辑。