Dia*_*onW 1 javascript d3.js nvd3.js
我目前正在尝试使用nvd3来构建条形图,到目前为止,离散条形图具有我需要的一切.但是,我正在努力尝试像其他图形一样添加图例.我已经做了类似的更改,在discreteBarGraph.js文件中添加了一个图例,但显然我错过了一些东西.有人对这个有经验么?谢谢.
离散条形图可能没有内置图例,但NVD3默认图例本身就是一个内置函数,您可以像NVD3图表函数一样调用它.
唯一复杂的部分是设置要在图例中显示的数据.在其他图表中,图例显示了系列名称; 但对于离散条形图,只有一个系列.我假设你想显示与每个条相关的标签,可能作为在x轴上显示它们的替代方法.
要实现这一点,您必须确保与调用图例函数的选择关联的数据数组是条形值和名称的数组,而不是最顶层的数据系列数组(在离散条形图中是一个数组) length-one包含单个系列对象的数组.)然后告诉图例函数如何使用该key(function(d){})方法从每个条形图的数据对象访问相应的标签.
以下是对这些更改的NVD3离散条示例的修改:
nv.addGraph(function() {
var chart = nv.models.discreteBarChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.tooltips(false)
.showValues(true)
.margin({top:50})//leave room for legend
chart.xAxis.tickFormat("") //don't show bar labels on axis
.axisLabel("Sector"); //show an axis title instead
//store svg selection in a variable so it can be re-used:
var svg = d3.select('#chart svg')
.datum(data);
//make the chart:
svg.transition().duration(500)
.call(chart);
var makeLegend = nv.models.legend()
//initialize legend function
.key(function(d) { return d.label; });
//tell the function which property to use as text
svg.append("g").attr("class", "legend")
//add a group to hold legend, position as necessary
//(no positioning will draw legend across top of SVG)
.datum(data[0].values)
//set data to the array of objects you want
//included in the legend
.transition().duration(500)
.call(makeLegend); //make it so
nv.utils.windowResize(chart.update);
nv.utils.windowResize(makeLegend); //doesn't seem to make much difference, but...
return chart;
});
Run Code Online (Sandbox Code Playgroud)
如果您以任何影响图例的方式更新数据,请记住您需要更新图例以及主图表.
| 归档时间: |
|
| 查看次数: |
4723 次 |
| 最近记录: |