d3.js多系列折线图 - 每个系列的颜色

时间:2015-05-29 16:01:19

标签: javascript d3.js

使用多系列折线图D3.js是否可以手动指定每一行的颜色?

data.csv

source_,track_index,alt,dist
series1,xxx,100,100
series1,xxx,200,200
series2,xxx,100,100
series2,xxx,200,200

.html文件

<!DOCTYPE html>
<style>
  body { font: 12px Arial;}
  path {stroke: steelblue;stroke-width: 2;fill: none;}
  .axis path,.axis line {fill: none;stroke: grey;stroke-width: 1;shape-rendering: crispEdges;}
  .line {fill: none;stroke: steelblue;stroke-width: 1.5px;}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>

<script>
var margin = {top: 30, right: 20, bottom: 30, left: 50},width = 1400 - margin.left - margin.right,height = 600 - margin.top - margin.bottom;

var parseDate = d3.time.format("%b %Y").parse; // Parse the date / time
var color = d3.scale.category10();

var x = d3.scale.linear().range([0,width]);
var y = d3.scale.linear().range([height, 0]);

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

var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);

var alt_line = d3.svg.line()
.x(function(d) { return x(d.dist_); })
.y(function(d) { return y(d.alt_); });

var svg = d3.select("body")
.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 + ")");

d3.csv("/data.csv", function(error, data) {

  data.forEach(function(d) {
    d.dist_ = d.dist;
    d.alt_ = d.alt;
});

x.domain([0, 30]); 
y.domain([0, 3000]); 

var dataNest = d3.nest()
.key(function(d) {return d.source_;})
.entries(data);

dataNest.forEach(function(d) { 
   svg.append("path")
   .attr("class", "line")
   .attr("d", alt_line(d.values)); 
});

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

svg.append("g")
.attr("class", "y axis")
.call(yAxis);

});
</script>
</body>

0 个答案:

没有答案