How do I change the legend position in a NVD3 chart?

拜拜、爱过 提交于 2019-11-30 08:26:43

There is AFAIK no option to do this, but you can select the g element that contains the legend manually and move it, e.g.

d3.select(".nv-legendWrap")
  .attr("transform", "translate(100,100)");
Michael

As of this writing (2 jul 2015) nvd3 supports putting the legend to the right of the pie chart.

When you initialize the graph, set legendPosition to right.

Example:

nv.addGraph(function() {
    var chart = nv.models.pieChart()
      .x(function(d) { return d.label })
      .y(function(d) { return d.value })          
      .legendPosition("right");


    svg.datum(piedata).call(chart);

  return chart;
});

See http://nvd3-community.github.io/nvd3/examples/documentation.html#pieChart

You can permanently change the position of the legend for an nvd3 chart model by editing the JS file itself. This may work better for chart refreshing than including the positioning in your initialization. Search the JS (like multiBarChart.js or lineChart.js) for: g.select('.nv-legendWrap'). An .attr will be defined just after that, replace that with:

.attr('transform', 'translate(10,270)')

Where 10 is the x value the legend is shifted and 270 is the y value it is shifted.

I've been trying to solve the same issue with a lineChart. First I just added a

d3.select('.nv-legendWrap').attr('transform', 'translate(0, 475)')

But it reverts back to default when you resize the chart. So I also copied the line and added it inside my windowResize() function, which worked. BUT then when I click the legend to hide/show lines it moves BACK to default position.

I think the best solution might be to edit the js file.

It seems like when it comes to charting there's just no easy solution. NVD3.js documentation is very lacking and limited. But D3.js is huge and also complicated...you just can't have both ease and customization, you have to give up one or the other.

Update: If you just need to move it a little you can simply do the following:

chart.legend.margin({top: 0, right: 0, left: 0, bottom: 20})
user3898336

You can adjust chart.legend.margin. It has top, right, left, bottom as attributes.

Androido

Doc on legend is here : http://nvd3-community.github.io/nvd3/examples/documentation.html#legend

as an example:

chart.legend.rightAlign(false);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!