score:2

Accepted answer

there are a few things to address here:

  1. create an x-axis label that is properly aligned
  2. split the long x-axis label over multiple lines (it's too long otherwise)
  3. set the css classes correctly for the title, notes, and other text elements

taking them in that order:

x-axis label under the axis, centered

the simplest way to do this is to append your text between the code where you draw the x-axis and the y-axis.

svg.append("text")    // text label for the x axis
  .attr("class", "notes")
  .attr("transform", "translate(" + width/2 + ")")
  .attr("y",  height + margin.bottom)
  .text(d.description)
  .call(splitlonglabel);    // the next section explains this bit...

split the long x-axis label over multiple lines

to do this, i've borrowed a little from this answer: https://stackoverflow.com/a/13275930/3442309

it looks like the most sensible place to split the d.description text is at the "-" character: this is how it's done on the screenshot of how you want the chart to look.

to achieve the split, user tspan elements

var insertlinebreaks = function (d) {
    var el = d;    // get the current element
    var words = d.text().split("-");    // split text  at the hyphen
    el.text('');
    for (var i = 0; i < words.length; i++) {    // then build up the tspans
        var tspan = el.append('tspan')
            .attr('x', 0)
            .text(words[i])
            .style("text-anchor", "middle");
        if (i > 0)
            tspan
                .attr('x', 0)
                .attr('dy', '15')
                .style("text-anchor", "middle");
    }
};

to change how and where this label is split, or to make it more generic (eg basing the split on length, rather than a specific character), simply modify how split is defined

setting css classes for text

in your example, the title was not using the title css class, so not getting the expected style. the reason for this is the following code at the end of your script:

svg.
    attr("class", "notes").
    append("text").
    text(d.description);

what this was doing was setting the notes style for all text in the svg. more correctly, you should have set the class attribute after appending the text.

correcting for this, for the title, we now have:

svg.
    //attr("class", "title"). <- removed from here
    append("text").
    attr("class", "title").    // <- added here
    html("gross domestic product </br>")

and i've added some positioning to the javascript for `title, rather than in the css:

    ....
    .attr('x', width / 2)
    .attr('y', 20)
    .style("text-anchor", "middle");

lastly, i've corrected your css, which used color for applying text color, instead of fill, which is the correct way

here's a fiddle with all the changes described: https://jsfiddle.net/henbox/nuwzxoz8/1/


Related Query

More Query from same tag