【问题标题】:How to add a legend to a discrete bar graph in nvd3?如何将图例添加到 nvd3 中的离散条形图?
【发布时间】:2014-01-22 01:41:30
【问题描述】:

我目前正在尝试使用 nvd3 构建条形图,到目前为止,离散条形图拥有我需要的一切。但是,我正在努力尝试像其他图表一样为其添加图例。我已经进行了类似的更改,在discreteBarGraph.js 文件中添加了一个图例,但很明显我遗漏了一些东西。有人对这个有经验么?谢谢。

【问题讨论】:

  • 能否贴出相关代码或提供示例(小提琴等)

标签: javascript d3.js nvd3.js


【解决方案1】:

离散条形图可能没有内置图例,但 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;
});

如果您以任何影响图例的方式更新数据,请记住您需要更新图例以及主图表。

【讨论】:

  • 非常感谢您的帮助,这正是我所需要的。您是否还知道如何添加控件,以便在单击图例时图形动画?如果没有,那很好。
  • 我不确定您要制作什么动画。控件通常在不同的可视化选项之间切换——离散条形图只有一个选项。如果您想要更高级的东西,请尝试使用多条形图。
  • 我最初开始尝试使用多条形图,但我无法让它以只接受单系列数据的方式运行。看这里 (stackoverflow.com/questions/21242620/…)
  • 我认为 OP 想要的是已弃用的带有图例 github.com/adjust/nvd3-old/blob/master/deprecated/… 的多栏
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
  • 2012-10-23
  • 1970-01-01
相关资源
最近更新 更多