如何在nvd3饼图图例中添加图像?

时间:2013-12-01 17:44:53

标签: nvd3.js

我想在nvd3饼图图例中添加图像而不是文本。 我有这个代码,但它只更改工具提示中的图像与图像。我想更改图例中带有相同图像的文本。

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;});

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

nvd3.js目前无法使用此功能。工具提示有效,因为您指定的img元素被设置为div元素中未包含的svg元素。它不适用于图例或图表标签,因为它们是使用svg text元素构建的。要在图表svg中显示图片,我们需要使用svg image元素。

如果我们破解nvd3.js代码,我们可以构建svg image元素。这里是你可以做些什么来推动传奇工作的概述。然后,您可以决定是否要在图表标签的nv.models.pie代码中尝试类似的内容,或者只是想在图表配置中将chart.showLabels设置为false

在数据中添加新密钥以提供图片路径:

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"
}  ];

更新nv.models.legend代码以显示图片:

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');

更新nv.models.legend代码以不显示密钥:

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

在确定图例布局时更新nv.models.legend代码以考虑图像宽度:

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