How do I change the legend position in a NVD3 char

2019-02-08 07:14发布

Does anyone know how to reposition the legend in a NVD3 chart relative to the graph itself?

It is on top by default, and I would like it to go on the side (better use of space within my app)

An example of what I would like to do: enter image description here

6条回答
\"骚年 ilove
2楼-- · 2019-02-08 07:19

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

查看更多
Ridiculous、
3楼-- · 2019-02-08 07:22

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

查看更多
冷血范
4楼-- · 2019-02-08 07:34

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})
查看更多
放荡不羁爱自由
5楼-- · 2019-02-08 07:36

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

as an example:

chart.legend.rightAlign(false);
查看更多
The star\"
6楼-- · 2019-02-08 07:37

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.

查看更多
虎瘦雄心在
7楼-- · 2019-02-08 07:40

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)");
查看更多
登录 后发表回答