How can i add an image in nvd3 piechart legend?

你。 提交于 2020-01-15 11:56:13

问题


I want to add an image in nvd3 piechart legend instead of text. I have this code but it changes only the text in the tooltip with the image. I want to change and the text in the legend with the same image.

var testdata = [
{
  key: "<img src="+"./imgs/facebook.jpg"+">",
  y: 1
},
{
  key: ""<img src="+"./imgs/twitter.jpg"+">"",
  y: 2 
}  ];
nv.addGraph(function() { 

var chart = nv.models.pieChart()
    .x(function(d) { return d.key})
    .labelThreshold(.08)
    .showLabels(true)
    .color(d3.scale.category10().range())
    .donut(true);



  chart.pie.donutLabelsOutside(true).donut(true);

  d3.select("#mypiechart")
    .datum(testdata)
    .transition().duration(1200)
    .call(chart);

return chart;});

Any ideas?


回答1:


This is not currently possible with nvd3.js. The tooltip works because the img element you have specified is being set into a div that isn't contained within the svg element. It doesn't work for the legend or chart labels because those are built using svg text elements. In order to show an image within the chart svg we'd need to use an svg image element.

We could build the svg image elements if we hack the nvd3.js code. Here's an outline of what you could do to get the legend working. You could then decide if you'd want to try something similar in the nv.models.pie code for the chart labels or if you'd just want to set chart.showLabels to false in your chart configuration.

Add a new key in your data to provide the image path:

var testdata = [
{
  key: "<img src="+"./imgs/facebook.jpg"+">",
  y: 1,
  image_path: "./imgs/facebook.jpg"
},
{
  key: "<img src="+"./imgs/twitter.jpg"+">",
  y: 2,
  image_path: "./imgs/twitter.jpg"
}  ];

Update the nv.models.legend code to show the image:

seriesEnter.append('circle')
    .style('stroke-width', 2)
    .attr('class','nv-legend-symbol')
    .attr('r', 5);
// Add an svg image into the legend
seriesEnter.append('image')
  .attr('xlink:href', function(d) { return d.image_path} )
  .attr('height',20)
  .attr('width',20)
  .attr('y', '-10')
  .attr('x', '8');

Update the nv.models.legend code to not show the key:

// Don't add the key value into the legend text
//series.select('text').text(getKey);

Update the nv.models.legend code to consider the image width when determining the legend layout:

//seriesWidths.push(nodeTextLength + 28); // 28 is ~ the width of the circle plus some padding
//Include image width...
seriesWidths.push(nodeTextLength + 48);


来源:https://stackoverflow.com/questions/20315208/how-can-i-add-an-image-in-nvd3-piechart-legend

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