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
424 views
in Technique[技术] by (71.8m points)

javascript - show label in tooltip but not in x axis for chartjs line chart

I currently am using a line chart with chart.js, and have a label set that looks like this ["January 2015", "February 2015", "March 2015", "April 2015", "May 2015", "June 2015"]. I want the relevant label to show up in the tooltip for the chart, but only want every alternating label to show up on the x axis of the chart to prevent crowding. Is there a way I can achieve this ?

I am currently replacing every second value from my array with "", but while that removes the crowding from my x axis, it does not meet my requirement to show the label in the tooltip.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Just extend the line chart and replace the xLabels you don't want after your initialization

Chart.types.Line.extend({
    name: "LineAlt",
    initialize: function (data) {
        Chart.types.Line.prototype.initialize.apply(this, arguments);
        var xLabels = this.scale.xLabels
        xLabels.forEach(function (label, i) {
            if (i % 2 == 1)
                xLabels[i] = '';
        })
    }
});


var lineChartData = {
    labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    datasets: [
        {
            fillColor: "#79D1CF",
            strokeColor: "#79D1CF",
            data: [59, 80, 81, 56, 55, 40, 34, 43, 43, 12, 65, 65]
        }
    ]
};

var ctx = document.getElementById("myChart").getContext("2d");
var myLine = new Chart(ctx).LineAlt(lineChartData);

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


enter image description here


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

...