Multi Line Ordinal d3 chart

廉价感情. 提交于 2019-12-06 01:45:57

This should get you started: http://jsfiddle.net/hU6r6/

Setting the domain of the xScale properly

// Find all the unique x-axis values
// Fortunately, alphabetical sorting of the values also yields
// the correct order
var xValues = d3.set(data.map(function (d) { return d.Half; })).values().sort();

// Set up the domain using only the unique values for the xAxis
var xScale = d3.scale.ordinal()
    .domain(xValues)
    // Setting the rangePoints instead of rangeBands
    .rangePoints([0, width], 0.5);

Append DOM elements tied to the data

// This is the same data as you have created
var supplierData = d3.nest().key(function(d) { return d.Supplier; }).entries(data); 

// Create a line object which will set the 'd' attributes for the paths
var line = d3.svg.line()
                  .interpolate("linear")
                  .x(function (d) { return xScale(d.Half); })
                  .y(function (d) { return yScale(d.Value); });

// To choose different colors
var colors = d3.scale.category10();

// The chart container
var gLines = svg.selectAll('g.chart-area').data([ supplierData ]);

gLines.enter()
  .append('g')
  .classed('chart-area', true)
  .attr('transform', 'translate(' + margin.left + ',' + margin.top + ")");

// Our 'paths' which are the lines
var lines = gLines.selectAll('path.supplier').data(function (d) { return d; });

// Our 'paths' which are the lines
lines.enter()
  .append('path')
  .classed('supplier', true)
  // The data is of the form { key: 'SupplierX', values: [ ... ] }
  .attr('d', function (d) { return line(d.values); })
  .attr('fill', 'none')
  .attr('stroke', function (d, i) { return colors(i); })

Next steps

If you followed the tutorial, then you will see that the jsFiddle only implements the enter phase of the data. Perhaps that is enough for your purposes and update and exit phases are not needed. Nevertheless, you should follow the tutorial completely.

Apart from that,this graph is still bare-bone and lacks proper y-axis and labels for the colors, etc.

You'll probably want to use an SVG path to represent each line. D3 has a line generator that can help with the line definition.

In it's simplest form it could look something like this with your data:

var line = d3.svg.line()
    .x(function(d) { return xScale(d.Half); })
    .y(function(d) { return yScale(d.Value); });

svg.selectAll("path")
    .data(data)
    .enter().append("path")
        .attr("d", function(d) { return line(d.values); });

You'll probably also want to set the fill and stroke styles to get the lines to look good and probably to color them individually using an ordinal color scale with Supplier as a domain.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!