How to add a title for a NVD3.js graph

帅比萌擦擦* 提交于 2019-11-27 22:33:54

You can use D3 to select the container SVG and append the title:

d3.select('#chart svg')
  .append("text")
  .attr("x", 200)             
  .attr("y", 100)
  .attr("text-anchor", "middle")  
  .text("Sample Charts");

This assumes that you're using the same ID etc for the SVG as in the NVD3 examples, if not, simply adjust the selector accordingly.

Taking a different approach, I wanted to have better control over the layout and style of the chart so instead of adding it as an text element inside the <svg> tag I added the title outside with help from jQuery.

var $svg = $('#chart svg');
$svg.parent().append('<div class="chart-title">Sample Charts</div>');

chart-title can be used to style the text element inside svg tags as well, but centering is much easier than having to use the width of the svg to set the x value like so:

svg.append('text')
    .attr('x', width / 2)
    .attr('y', 20)
    .attr('text-anchor', 'middle')
    .attr('class', 'chart-title')
    .text('Sample Charts');

The above solution only works if you are setting the width. In my case the width was set to auto so until it created the chart it didn't have a width to refference. I actually modified the nvd3 code because I thought it was silly that some charts had titles and some didn't. There were 3 places I modified in each chart. Inside the margin section I added

var margin = {top: 30, right: 30, bottom: 30, left: 60}
    , marginTop = null
    .
    .
    .
    , title = false
    ;

Inside the chart function I added

function chart(selection) {
    .
    .
    .
    if(title) { 
        g.append("text")
            .attr("x", (availableWidth - margin.left)/ 2)             
            .attr("y", -4)
            .attr("text-anchor", "middle")  
            .text(title);
    }

Inside the chart options I added

chart._options = Object.create({}, {
        // simple options, just get/set the necessary values
        width:      {get: function(){return width;}, set: function(_){width=_;}},
        .
        .
        .
        title:      {get: function(){return title;}, set: function(_){title=_;}},

Then in your controller or where ever use

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