我目前正在尝试使用 nvd3 构建条形图,到目前为止,离散条形图具有我需要的一切。但是,我正在努力尝试像其他图表一样为其添加图例。我已经进行了类似的更改以在 discreteBarGraph.js 文件中添加图例,但很明显我遗漏了一些东西。有人对这个有经验么?谢谢。
最佳答案
离散条形图可能没有内置图例,但 NVD3 默认图例本身就是一个内置函数,您可以像调用 NVD3 图表函数一样调用它。
唯一复杂的部分是设置要在图例中显示的数据。在其他图中,图例显示系列名称;但对于离散条形图,只有一个系列。我假设您想显示与每个条相关的标签,可能作为在 x 轴上显示它们的替代方法。
要做到这一点,您必须确保与调用图例函数的选择相关联的数据数组是条形值和名称的数组,而不是最顶层的数据系列数组(在离散条形图中图表是一个长度为一的数组,其中包含单个系列对象。)然后您告诉图例函数如何使用 key(function(d){})
方法从每个柱的数据对象访问适当的标签.
这是对 NVD3 discrete bar example 的改编有了这些变化:
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;
});
如果您以任何影响图例的方式更新数据,请记住您需要更新图例和主图表。
关于javascript - 如何将图例添加到 nvd3 中的离散条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21272606/