问题
I am trying to define a lineChart in nvd3 with a domain scale on the x-axis. I can't get it to work. The first issue is that the voronoi code blows up. But even if I turn voronoi off, the x-axis still just shows a range of -1 to 1, instead of my domain values.
I think a workaround would be to assign numbers to the x-axis values, and then use a tick function to draw the text. But I want to figure out why I can't make it work with an ordinal scale.
Below is the code I have tried. My data works with other models, so I think the data is ok. I tried using the xDomain function to set the domain, and I also tried using the xAxis property to set a custom scale. Neither one seemed to do anything.
Code:
var lineData = [{ "key": "% Kernel CPU", "values": [{ "x": "Exe1", "y": 6.693271 }, { "x": "Exe2", "y": 0.8129451 }, { "x": "Exe3", "y": 71.3511437 }] },
{ "key": "% User CPU", "values": [{ "x": "Exe1", "y": 93.7063302 }, { "x": "Exe2", "y": 23.158042000000002 }, { "x": "Exe3", "y": 74.19397850000001 }] }];
var xdomain = ["Exe1", "Exe2", "Exe3"];
$('#test').append('<svg style="width:100%;height:400px;"></svg>');
nv.addGraph(function () {
var chartObj = nv.models.lineChart();
chartObj.lines.scatter.useVoronoi(false);
chartObj.xAxis.tickFormat(function (d) {
if (d.length > 15) {
return d.substring(0, 13) + '...';
}
return d;
});
chartObj.yAxis.tickFormat(d3.format('.1f'));
//Attempt1:
chartObj.xDomain(xdomain);
//Attempt2:
//var xScale = d3.scale.ordinal();
//xScale.domain(xdomain);
//chartObj.xAxis.scale(xScale);
//Attempt3:
//chartObj.xAxis.domain(xdomain);
d3.select('#test svg').datum(lineData)
.transition().duration(500).call(chartObj);
return chartObj;
});
回答1:
I think the problem lies in these lines in the models.scatter definition:
if ( isNaN(x.domain()[0])) {
x.domain([-1,1]);
}
if ( isNaN(y.domain()[0])) {
y.domain([-1,1]);
}
Obviously this will disallow any ordinal scales for the x or y scales in this type of chart (which underlies the line chart and most of the other non-bar charts it seems).
来源:https://stackoverflow.com/questions/17887542/how-can-i-specify-a-domain-x-axis-in-nvd3-linechart