【发布时间】:2014-01-22 01:41:30
【问题描述】:
我目前正在尝试使用 nvd3 构建条形图,到目前为止,离散条形图拥有我需要的一切。但是,我正在努力尝试像其他图表一样为其添加图例。我已经进行了类似的更改,在discreteBarGraph.js 文件中添加了一个图例,但很明显我遗漏了一些东西。有人对这个有经验么?谢谢。
【问题讨论】:
-
能否贴出相关代码或提供示例(小提琴等)
标签: javascript d3.js nvd3.js
我目前正在尝试使用 nvd3 构建条形图,到目前为止,离散条形图拥有我需要的一切。但是,我正在努力尝试像其他图表一样为其添加图例。我已经进行了类似的更改,在discreteBarGraph.js 文件中添加了一个图例,但很明显我遗漏了一些东西。有人对这个有经验么?谢谢。
【问题讨论】:
标签: javascript d3.js nvd3.js
离散条形图可能没有内置图例,但 NVD3 默认图例本身就是一个内置函数,您可以像调用 NVD3 图表函数一样调用它。
唯一复杂的部分是设置要在图例中显示的数据。在其他图表中,图例显示系列名称;但对于离散条形图,只有一个系列。我假设您想显示与每个条相关联的标签,可能作为在 x 轴上显示它们的替代方法。
要做到这一点,您必须确保与调用图例函数的选择关联的数据数组是条形值和名称的数组,而不是数据系列的最顶层数组(在离散条形chart 是一个长度为一的数组,包含单个系列对象。)然后您告诉 legend 函数如何使用 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;
});
如果您以任何影响图例的方式更新数据,请记住您需要更新图例以及主图表。
【讨论】: