使chart.js中的X轴标签以一定比例递增

问题描述 投票:13回答:2

我的标签范围是50-90,并且其中的每个数字都显示在其中。

我想将标签按5或10列出,因为当前它们都在一起处理了。

也使y轴的左侧部分被切除。

javascript chart.js
2个回答
29
投票

编辑2:好的,所以我实际上正在一个项目中需要这样的功能,所以我制作了一个Chart.js的自定义版本以包含此功能。http://jsfiddle.net/leighking2/mea767ss/https://github.com/leighquince/Chart.js

这是下面两种解决方案的组合,但绑定到CHart.js的核心,因此无需指定自定义比例和图表。

折线图和条形图都有一个名为的新选项

labelsFilter:function(label, index){return false;)

默认情况下,它将仅返回false,因此将显示x轴上的所有标签,但是如果通过过滤器作为选项,则它将过滤标签

所以这是条形和线形的示例

var ctx = document.getElementById("chart").getContext("2d");
var data = {
    labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
    datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.5)",
        strokeColor: "rgba(220,220,220,0.8)",
        highlightFill: "rgba(220,220,220,0.75)",
        highlightStroke: "rgba(220,220,220,1)",

        data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
    }]
};


var myLineChart = new Chart(ctx).Line(data, {
    labelsFilter: function (value, index) {
        return (index + 1) % 5 !== 0;
    }
});
<script src="http://quincewebdesign.com/cdn/Chart.js"></script>
<canvas id="chart" width="1200px"></canvas>

原始答案

您可以覆盖比例绘制功能以实现此目的。我唯一不喜欢的是,它会应用于您的所有图形,因此另一个选择是使用可覆盖绘制的自定义图形类型。

EDIT 1:刚刚意识到,可以通过使用索引值而不是标签来实现相同的效果,然后可以将其应用于所有标签类型,而不仅仅是数字标签,这适用于两个示例,并且很容易改变了。这是第二个使用索引而不是标签http://jsfiddle.net/leighking2/n9c8jx55/

的示例

1st-覆盖比例绘制功能 http://jsfiddle.net/leighking2/96grgz0d/

仅更改此处是在绘制x轴标签之前,我们测试标签是否为数字,并且除以5时其余数是否不等于0(因此,不能将数字除以5)如果同时符合这两个条件,我们不会绘制标签

Chart.Scale = Chart.Scale.extend({
   draw : function(){
           console.log(this);
           var helpers = Chart.helpers;
           var each = helpers.each;
           var aliasPixel = helpers.aliasPixel;
              var toRadians = helpers.radians;
            var ctx = this.ctx,
                yLabelGap = (this.endPoint - this.startPoint) / this.steps,
                xStart = Math.round(this.xScalePaddingLeft);
            if (this.display){
                ctx.fillStyle = this.textColor;
                ctx.font = this.font;
                each(this.yLabels,function(labelString,index){
                    var yLabelCenter = this.endPoint - (yLabelGap * index),
                        linePositionY = Math.round(yLabelCenter);

                    ctx.textAlign = "right";
                    ctx.textBaseline = "middle";
                    if (this.showLabels){
                        ctx.fillText(labelString,xStart - 10,yLabelCenter);
                    }
                    ctx.beginPath();
                    if (index > 0){
                        // This is a grid line in the centre, so drop that
                        ctx.lineWidth = this.gridLineWidth;
                        ctx.strokeStyle = this.gridLineColor;
                    } else {
                        // This is the first line on the scale
                        ctx.lineWidth = this.lineWidth;
                        ctx.strokeStyle = this.lineColor;
                    }

                    linePositionY += helpers.aliasPixel(ctx.lineWidth);

                    ctx.moveTo(xStart, linePositionY);
                    ctx.lineTo(this.width, linePositionY);
                    ctx.stroke();
                    ctx.closePath();

                    ctx.lineWidth = this.lineWidth;
                    ctx.strokeStyle = this.lineColor;
                    ctx.beginPath();
                    ctx.moveTo(xStart - 5, linePositionY);
                    ctx.lineTo(xStart, linePositionY);
                    ctx.stroke();
                    ctx.closePath();

                },this);

                each(this.xLabels,function(label,index){
                    //================================
                    //test to see if we draw the label
                    //================================
                    if(typeof label === "number" && label%5 != 0){
                     return;   
                    }
                    var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
                        // Check to see if line/bar here and decide where to place the line
                        linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
                        isRotated = (this.xLabelRotation > 0);

                    ctx.beginPath();

                    if (index > 0){
                        // This is a grid line in the centre, so drop that
                        ctx.lineWidth = this.gridLineWidth;
                        ctx.strokeStyle = this.gridLineColor;
                    } else {
                        // This is the first line on the scale
                        ctx.lineWidth = this.lineWidth;
                        ctx.strokeStyle = this.lineColor;
                    }
                    ctx.moveTo(linePos,this.endPoint);
                    ctx.lineTo(linePos,this.startPoint - 3);
                    ctx.stroke();
                    ctx.closePath();


                    ctx.lineWidth = this.lineWidth;
                    ctx.strokeStyle = this.lineColor;


                    // Small lines at the bottom of the base grid line
                    ctx.beginPath();
                    ctx.moveTo(linePos,this.endPoint);
                    ctx.lineTo(linePos,this.endPoint + 5);
                    ctx.stroke();
                    ctx.closePath();

                    ctx.save();
                    ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
                    ctx.rotate(toRadians(this.xLabelRotation)*-1);

                    ctx.textAlign = (isRotated) ? "right" : "center";
                    ctx.textBaseline = (isRotated) ? "middle" : "top";
                    ctx.fillText(label, 0, 0);
                    ctx.restore();

                },this);

            }
        } 
});

然后,我们可以像正常使用图。声明数据

var ctx = document.getElementById("chart").getContext("2d");
var data = {
    labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
    datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.2)",
        strokeColor: "rgba(220,220,220,1)",
        pointColor: "rgba(220,220,220,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: [65, 34, 21, 11, 11, 34, 34, 12, 24, 45, 65, 34, 21, 11, 11, 34, 34, 12, 24, 45, 65, 34, 21, 11, 11, 34, 34, 12, 24, 45]
    }, ]
};

绘制图形

var myLineChart = new Chart(ctx).Line(data);

第二个自定义图形+自定义比例+过滤功能 http://jsfiddle.net/leighking2/6xej5ek3/

在这种方法中,我们仍然需要创建一个自定义比例对象,但是我们可以选择仅将其应用于声明的对象,而不是将其应用于所有创建的图表。同样在此示例中,我们还可以使过滤器成为在运行时应用的函数,因此我们可以让每个图对标签进行不同过滤]

第一个比例尺对象

Chart.CustomScale = Chart.Scale.extend({
    draw: function () {
        console.log(this);
        var helpers = Chart.helpers;
        var each = helpers.each;
        var aliasPixel = helpers.aliasPixel;
        var toRadians = helpers.radians;
        var ctx = this.ctx,
            yLabelGap = (this.endPoint - this.startPoint) / this.steps,
            xStart = Math.round(this.xScalePaddingLeft);
        if (this.display) {
            ctx.fillStyle = this.textColor;
            ctx.font = this.font;
            each(this.yLabels, function (labelString, index) {
                var yLabelCenter = this.endPoint - (yLabelGap * index),
                    linePositionY = Math.round(yLabelCenter);

                ctx.textAlign = "right";
                ctx.textBaseline = "middle";
                if (this.showLabels) {
                    ctx.fillText(labelString, xStart - 10, yLabelCenter);
                }
                ctx.beginPath();
                if (index > 0) {
                    // This is a grid line in the centre, so drop that
                    ctx.lineWidth = this.gridLineWidth;
                    ctx.strokeStyle = this.gridLineColor;
                } else {
                    // This is the first line on the scale
                    ctx.lineWidth = this.lineWidth;
                    ctx.strokeStyle = this.lineColor;
                }

                linePositionY += helpers.aliasPixel(ctx.lineWidth);

                ctx.moveTo(xStart, linePositionY);
                ctx.lineTo(this.width, linePositionY);
                ctx.stroke();
                ctx.closePath();

                ctx.lineWidth = this.lineWidth;
                ctx.strokeStyle = this.lineColor;
                ctx.beginPath();
                ctx.moveTo(xStart - 5, linePositionY);
                ctx.lineTo(xStart, linePositionY);
                ctx.stroke();
                ctx.closePath();

            }, this);

            each(this.xLabels, function (label, index) {
                //======================================================
                //apply the filter the the label if it is a function
                //======================================================
                if (typeof this.labelsFilter === "function" && this.labelsFilter(label)) {
                    return;
                }
                var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
                    // Check to see if line/bar here and decide where to place the line
                    linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
                    isRotated = (this.xLabelRotation > 0);

                ctx.beginPath();

                if (index > 0) {
                    // This is a grid line in the centre, so drop that
                    ctx.lineWidth = this.gridLineWidth;
                    ctx.strokeStyle = this.gridLineColor;
                } else {
                    // This is the first line on the scale
                    ctx.lineWidth = this.lineWidth;
                    ctx.strokeStyle = this.lineColor;
                }
                ctx.moveTo(linePos, this.endPoint);
                ctx.lineTo(linePos, this.startPoint - 3);
                ctx.stroke();
                ctx.closePath();


                ctx.lineWidth = this.lineWidth;
                ctx.strokeStyle = this.lineColor;


                // Small lines at the bottom of the base grid line
                ctx.beginPath();
                ctx.moveTo(linePos, this.endPoint);
                ctx.lineTo(linePos, this.endPoint + 5);
                ctx.stroke();
                ctx.closePath();

                ctx.save();
                ctx.translate(xPos, (isRotated) ? this.endPoint + 12 : this.endPoint + 8);
                ctx.rotate(toRadians(this.xLabelRotation) * -1);

                ctx.textAlign = (isRotated) ? "right" : "center";
                ctx.textBaseline = (isRotated) ? "middle" : "top";
                ctx.fillText(label, 0, 0);
                ctx.restore();

            }, this);

        }
    }
});

现在将使用此比例尺的自定义图,很烦人的是,我们必须重写整个buildscale函数

Chart.types.Line.extend({
    name: "LineAlt",
    initialize: function (data) {
        //======================================================
        //ensure the new option is part of the options
        //======================================================
        this.options.labelsFilter = data.labelsFilter || null;
        Chart.types.Line.prototype.initialize.apply(this, arguments);


    },
    buildScale: function (labels) {
        var helpers = Chart.helpers;
        var self = this;

        var dataTotal = function () {
            var values = [];
            self.eachPoints(function (point) {
                values.push(point.value);
            });

            return values;
        };
        var scaleOptions = {
            templateString: this.options.scaleLabel,
            height: this.chart.height,
            width: this.chart.width,
            ctx: this.chart.ctx,
            textColor: this.options.scaleFontColor,
            fontSize: this.options.scaleFontSize,
            //======================================================
            //pass this new options to the scale object
            //======================================================
            labelsFilter: this.options.labelsFilter,
            fontStyle: this.options.scaleFontStyle,
            fontFamily: this.options.scaleFontFamily,
            valuesCount: labels.length,
            beginAtZero: this.options.scaleBeginAtZero,
            integersOnly: this.options.scaleIntegersOnly,
            calculateYRange: function (currentHeight) {
                var updatedRanges = helpers.calculateScaleRange(
                dataTotal(),
                currentHeight,
                this.fontSize,
                this.beginAtZero,
                this.integersOnly);
                helpers.extend(this, updatedRanges);
            },
            xLabels: labels,
            font: helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
            lineWidth: this.options.scaleLineWidth,
            lineColor: this.options.scaleLineColor,
            gridLineWidth: (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
            gridLineColor: (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
            padding: (this.options.showScale) ? 0 : this.options.pointDotRadius + this.options.pointDotStrokeWidth,
            showLabels: this.options.scaleShowLabels,
            display: this.options.showScale
        };

        if (this.options.scaleOverride) {
            helpers.extend(scaleOptions, {
                calculateYRange: helpers.noop,
                steps: this.options.scaleSteps,
                stepValue: this.options.scaleStepWidth,
                min: this.options.scaleStartValue,
                max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
            });
        }

        //======================================================
        //Use the new Custom Scal that will make use of a labelsFilter function
        //======================================================
        this.scale = new Chart.CustomScale(scaleOptions);
    }
});

然后我们可以像平常一样使用它。声明数据,但是这次为labelsFilter传递了一个新选项,该选项可以应用对x标签的过滤功能

var ctx = document.getElementById("chart").getContext("2d");
var data = {
    labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
    labelsFilter: function (label) {
        //return true if this label should be filtered out
        return label % 5 !== 0;
    },
    datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.2)",
        strokeColor: "rgba(220,220,220,1)",
        pointColor: "rgba(220,220,220,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: [65, 34, 21, 11, 11, 34, 34, 12, 24, 45, 65, 34, 21, 11, 11, 34, 34, 12, 24, 45, 65, 34, 21, 11, 11, 34, 34, 12, 24, 45]
    }, ]
};

然后使用新的自定义图形名称绘制图形

var myLineChart = new Chart(ctx).LineAlt(data);

总的来说,尽管涉及更多点,但我更喜欢第二种方法,因为这意味着可以将自定义过滤器应用于我声明的每个图形。


0
投票

我更新了提供的代码段,以防止x轴标签旋转。另外,一些参数没有在构造函数中传递。检查// Mike Walder的注释。

 //Code to manually set the interval of X-Axis Labels: From http://jsfiddle.net/leighking2/n9c8jx55/
        Chart.CustomScale = Chart.Scale.extend({
            draw: function () {
                var helpers = Chart.helpers;
                var each = helpers.each;
                var aliasPixel = helpers.aliasPixel;
                var toRadians = helpers.radians;
                var ctx = this.ctx,
                    yLabelGap = (this.endPoint - this.startPoint) / this.steps,
                    xStart = Math.round(this.xScalePaddingLeft);
                if (this.display) {
                    ctx.fillStyle = this.textColor;
                    ctx.font = this.font;
                    each(this.yLabels, function (labelString, index) {
                        var yLabelCenter = this.endPoint - (yLabelGap * index),
                            linePositionY = Math.round(yLabelCenter);

                        ctx.textAlign = "right";
                        ctx.textBaseline = "middle";
                        if (this.showLabels) {
                            ctx.fillText(labelString, xStart - 10, yLabelCenter);
                        }
                        ctx.beginPath();
                        if (index > 0) {
                            // This is a grid line in the centre, so drop that
                            ctx.lineWidth = this.gridLineWidth;
                            ctx.strokeStyle = this.gridLineColor;
                        } else {
                            // This is the first line on the scale
                            ctx.lineWidth = this.lineWidth;
                            ctx.strokeStyle = this.lineColor;
                        }

                        linePositionY += helpers.aliasPixel(ctx.lineWidth);

                        ctx.moveTo(xStart, linePositionY);
                        ctx.lineTo(this.width, linePositionY);
                        ctx.stroke();
                        ctx.closePath();

                        ctx.lineWidth = this.lineWidth;
                        ctx.strokeStyle = this.lineColor;
                        ctx.beginPath();
                        ctx.moveTo(xStart - 5, linePositionY);
                        ctx.lineTo(xStart, linePositionY);
                        ctx.stroke();
                        ctx.closePath();

                    }, this);

                    each(this.xLabels, function (label, index) {
                        //======================================================
                        //apply the filter to the index if it is a function
                        //======================================================
                        if (typeof this.labelsFilter === "function" && this.labelsFilter(index)) {
                            return;
                        }
                        //Hack by Mike Walder to enforce X-Labels are Written horizontally
                        var xLabelRot = this.xLabelRotation;
                        this.xLabelRotation = 0;
                        //End of Hack
                        var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
                            // Check to see if line/bar here and decide where to place the line
                            linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
                            //Mike Walder: isRotated nees original Roation Value to display the X-Label in the RollOver Area of a Datapoint
                            isRotated = true;(xLabelRot > 0);

                        ctx.beginPath();
                    if(this.scaleShowVerticalLines){
                            if (index > 0) {
                                // This is a grid line in the centre, so drop that
                                ctx.lineWidth = this.gridLineWidth;
                                ctx.strokeStyle = this.gridLineColor;
                            } else {
                                // This is the first line on the scale
                                ctx.lineWidth = this.lineWidth;
                                ctx.strokeStyle = this.lineColor;
                            }
                            ctx.moveTo(linePos, this.endPoint);
                            ctx.lineTo(linePos, this.startPoint - 3);
                            ctx.stroke();
                            ctx.closePath();


                            ctx.lineWidth = this.lineWidth;
                            ctx.strokeStyle = this.lineColor;
                        }
                        // Small lines at the bottom of the base grid line
                        ctx.beginPath();
                        ctx.moveTo(linePos, this.endPoint);
                        ctx.lineTo(linePos, this.endPoint + 5);
                        ctx.stroke();
                        ctx.closePath();

                        ctx.save();
                        ctx.translate(xPos, (isRotated) ? this.endPoint + 12 : this.endPoint + 8);
                        ctx.rotate(toRadians(this.xLabelRotation) * -1);

                        //Mike Walder added center here, because it looks better if the label designator is in the center of the smal line
                        ctx.textAlign = "center";
                        ctx.textBaseline = (isRotated) ? "middle" : "top";
                        ctx.fillText(label, 0, 0);
                        ctx.restore();

                    }, this);

                }
            }
        });

Chart.types.Line.extend({
            name: "LineAlt",
            initialize: function (data) {
                //======================================================
                //ensure the new option is part of the options
                //======================================================
                this.options.labelsFilter = data.labelsFilter || null;
                Chart.types.Line.prototype.initialize.apply(this, arguments);

            },
            buildScale: function (labels) {
                var helpers = Chart.helpers;
                var self = this;

                var dataTotal = function () {
                    var values = [];
                    self.eachPoints(function (point) {
                        values.push(point.value);
                    });

                    return values;
                };
                var scaleOptions = {
                    // Mike Walder: added this configuration option since it is overridden in the new code
                    scaleShowVerticalLines: this.options.scaleShowVerticalLines,
                    templateString: this.options.scaleLabel,
                    height: this.chart.height,
                    width: this.chart.width,
                    ctx: this.chart.ctx,
                    textColor: this.options.scaleFontColor,
                    fontSize: this.options.scaleFontSize,
                    //======================================================
                    //pass this new options to the scale object
                    //======================================================
                    labelsFilter: this.options.labelsFilter,
                    fontStyle: this.options.scaleFontStyle,
                    fontFamily: this.options.scaleFontFamily,
                    valuesCount: labels.length,
                    beginAtZero: this.options.scaleBeginAtZero,
                    integersOnly: this.options.scaleIntegersOnly,
                    calculateYRange: function (currentHeight) {
                        var updatedRanges = helpers.calculateScaleRange(
                        dataTotal(),
                        currentHeight,
                        this.fontSize,
                        this.beginAtZero,
                        this.integersOnly);
                        helpers.extend(this, updatedRanges);
                    },
                    xLabels: labels,
                    font: helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
                    lineWidth: this.options.scaleLineWidth,
                    lineColor: this.options.scaleLineColor,
                    gridLineWidth: (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
                    gridLineColor: (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
                    padding: (this.options.showScale) ? 0 : this.options.pointDotRadius + this.options.pointDotStrokeWidth,
                    showLabels: this.options.scaleShowLabels,
                    display: this.options.showScale
                };

                if (this.options.scaleOverride) {
                    helpers.extend(scaleOptions, {
                        calculateYRange: helpers.noop,
                        steps: this.options.scaleSteps,
                        stepValue: this.options.scaleStepWidth,
                        min: this.options.scaleStartValue,
                        max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
                    });
                }

                //======================================================
                //Use the new Custom Scal that will make use of a labelsFilter function
                //======================================================
                this.scale = new Chart.CustomScale(scaleOptions);
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.