How to add a title for a NVD3.js graph

2019-01-14 19:50发布

问题:

I want to add a title text over the graph in NVD3.js.

I tried the following,

nv.addGraph(function() {
var chart = nv.models.linePlusBarWithFocusChart()
    .margin({top: 30, right: 60, bottom: 50, left: 70})
    .x(function(d,i) { return i })
    .color(d3.scale.category10().range());

chart.append("text")
    .attr("x", 200)             
    .attr("y", 100)
    .attr("text-anchor", "middle")  
    .text("Sample Charts");
}

Its (Highlighted) working for D3.js but not working for NVD3.js. I'm getting a Blank page..

I want to place the text over the Chart as like the following image (Which is created in Paint)

How can I achieve this?

回答1:

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.



回答2:

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


回答3:

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


标签: d3.js nvd3.js