甜甜圈饼图 - 添加标题 - NVd3.js

时间:2013-04-25 18:27:29

标签: javascript d3.js pie-chart nvd3.js

我正在探索NVD3.js库。令我惊讶的是,它能在多快的速度下生成。

但有时似乎很难改变图表。在这种情况下,我想为我的图表添加标题

另一方面,我想在工具提示中添加其他数据。所以在悬停时,它还会在我的数据中包含注释。

数据样本:

var data = [
{
  key: "Loans",
  y: 52.24
  note: "Expect greatest value"
}];

这是我正在玩的代码:

nv.addGraph(function() {

var width = 500,
    height = 500;

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

chart.pie
    .startAngle(function(d) { return d.startAngle/2 -Math.PI/2; })
    .endAngle(function(d) { return d.endAngle/2 -Math.PI/2 ;});


  d3.select("#chart")
      //.datum(historicalBarChart)
      .datum([data])
    .transition().duration(1200)
      .attr('width', width)
      .attr('height', height)
      .call(chart);

return chart;
});

Donut-Pie Chart example


更新:工具提示的原始代码位于src->models->pieChart.js内:

tooltip = function(key, y, e, graph) {
    return '<h3>' + key + '</h3>' +
           '<p> Confidence: ' +  y + '%</p>'
  }

我尝试用我自己的功能覆盖它。但要么得到错误要么没有改变。

标题更新:我通常会使用以下代码(或类似内容)作为标题。

svg.append("text")
    .attr("x", (width / 2))
    .attr("y", 0 - (margin.top / 2))
    .attr("text-anchor", "middle")
    .style("font-size", "16px")
    .style("text-decoration", "underline")
    .text("Awesome Title");

但当然,这在NVD3中无效。我不知道用什么函数来指定标题。

1 个答案:

答案 0 :(得分:5)

我认为你正在寻找图表。tooltipContent()JSFiddle:http://jsbin.com/idosop/7/edit

      var tp = function(key, y, e, graph) {
            console.log(key, e, y);
            return '<h3>' + key + '</h3>' +
                   '<p>!!' +  y + '!!</p>' +
              '<p>Likes: ' +  e.point.likes + '</p>';
      };
      chart.tooltipContent(tp);