我使用nvd3 js创建了一个历史条形图。我想在单击一个条形时获取相应x轴标签的值。如何在nvd3.js历史图表中获取矩形条点击事件对应的x轴标签值?
我目前的代码是
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="../build/nv.d3.css" rel="stylesheet" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.2/d3.min.js" charset="utf-8"></script>
<script src="../build/nv.d3.js"></script>
<style>
text {
font: 12px sans-serif;
}
svg {
display: block;
}
html, body, svg {
margin: 0px;
padding: 0px;
height: 100%;
width: 100%;
}
</style>
</head>
<body class='with-3d-shadow with-transitions'>
<svg id="test1"></svg>
<script>
var chart;
nv.addGraph(function() {
chart = nv.models.historicalBarChart();
chart
.margin({left: 100, bottom: 100})
.useInteractiveGuideline(true)
.duration(250)
;
// chart sub-models (ie. xAxis, yAxis, etc) when accessed directly, return themselves, not the parent chart, so need to chain separately
chart.xAxis
.axisLabel("Time (s)")
.tickFormat(d3.format(',.1f'));
chart.yAxis
.axisLabel('Voltage (v)')
.tickFormat(d3.format(',.2f'));
chart.showXAxis(true);
d3.select('#test1')
.datum(sinData())
.transition()
.call(chart);
var rectArray=d3.select('g.nv-bars').selectAll('rect').on('click',function(d,i){alert(d+i)});
nv.utils.windowResize(chart.update);
return chart;
});
//Simple test data generators
function sinAndCos() {
var sin = [],
cos = [];
for (var i = 0; i < 100; i++) {
sin.push({x: i*2, y: Math.sin(i/10)});
cos.push({x: i, y: .5 * Math.cos(i/10)});
}
return [
{values: sin, key: "Sine Wave", color: "#ff7f0e"},
{values: cos, key: "Cosine Wave", color: "#2ca02c"}
];
}
function sinData() {
var sin = [];
for (var i = 0; i < 100; i++) {
sin.push({x: i, y: Math.sin(i/10) * Math.random() * 100});
}
return [{
values: sin,
key: "Sine Wave",
color: "#ff7f0e"
}];
}
</script>
</body>
</html>