Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 views
in Technique[技术] by (71.8m points)

javascript - How to set ChartJS x-axis title

We are using Chartjs to plot the charts ,However there is no to give the x-axis titles,There is a solution for y-Axis title in here , But for x-Axis I could add the x axis name but could not create the space below the chart to properly place it , using y as this.chart.height overlapped the text with x axis title.

I have looked the chartjs v2.0 but it also does not have support for x-Axis title.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We set the height of the chart depending on how much height we want for the x axis label and then write in that space.

We don't have to do anything in the draw override because the canvas clearing too happens based on the height (that we adjusted)

Preview

enter image description here


Script

Chart.types.Line.extend({
    name: "LineAlt",
    initialize: function (data) {
        this.chart.height -= 30;

        Chart.types.Line.prototype.initialize.apply(this, arguments);

        var ctx = this.chart.ctx;
        ctx.save();
        // text alignment and color
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";
        ctx.fillStyle = this.options.scaleFontColor;
        // position
        var x = this.chart.width / 2;
        var y = this.chart.height + 15 + 5;
        // change origin
        ctx.translate(x, y)
        ctx.fillText("My x axis label", 0, 0);
        ctx.restore();
    }
});

and then

...
new Chart(ctx).LineAlt(data);

Fiddle - http://jsfiddle.net/ct2h2wde/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...