如何更改Y轴标签 [英] How to change Y axis labels

查看:66
本文介绍了如何更改Y轴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Chartjs制作折线图。
如何将y轴标签更改为颜色? (即红色代表1,绿色代表2,黑色代表3,..)

解决方案

更新我现在已在 https://github.com/leighquince/Chart的chartjs分支中添加了此功能。 js ,这意味着您不必覆盖或扩展新的图表类型。只需像普通方式一样传递选项,这是一个示例 http://fiddle.jshell.net/leighking2/ jLzvhf4f /



因此,可以通过覆盖比例绘制方法来运行我们在声明图表时提供的自定义函数,而不仅仅是添加。 p>

下面是代码段,但正如在这里所做的解释一样


  1. 创建了一个新图表并覆盖了buildScale方法,以传递名为 customYLabel 的新选项。这是您在声明图表时传递给图表的选项,它具有4个参数;标签的值,x位置,y位置,画布,标签的索引


    1. 构建比例还利用自定义比例尺

    2. 创建自定义比例尺,该自定义比例尺覆盖正常的比例尺绘制方法来检查此customYLabel选项,并在存在时使用它


重置是正常的,您的customYLabel所做的取决于您,但至少应调用`ctx.fillText (值,x,y),以便在画布上绘制标签。在下面的示例中,我根据标签的索引为标签上色,但是选项很多。



(如果更容易查看 http://fiddle.jshell.net/leighking2/2cac5t34/



  //提取帮助程序,因此我们可以在自定义比例类中使用它们。varhelpers = Chart.helpers,每个= helpers.each,aliasPixel = helpers.aliasPixel,toRadians = helpers.radians; / / new折线图,其构建比例将被覆盖,它将通过新选项customYLabel Chart.types.Line.extend({//传入名称以相同的名称在Chart命名空间中注册此图表: LineAlt,初始化:函数(数据){Chart.types.Line.prototype.initialize.apply(this,arguments);},buildScale:fun (标签){var self = this; var dataTotal = function(){var values = []; self.eachPoints(function(point){values.push(point.value);});返回值; }; var scaleOptions = {templateString:this.options.scaleLabel,高度:this.chart.height,宽度:this.chart.width,ctx:this.chart.ctx,textColor:this.options.scaleFontColor,fontSize:this.options。 scaleFontSize,fontStyle:this.options.scaleFontStyle,fontFamily:this.options.scaleFontFamily,valuesCount:labels.length,beginAtZero:this.options.scaleBeginAtZero,integersOnly:this.options.scaleIntegersOnly,//自定义y标签customYLabel的新选项: this.options.customYLabel,calculateYRange:function(currentHeight){var UpdatedRanges = helpers.calculateScaleRange(dataTotal(),currentHeight,this.fontSize,this.beginAtZero,this.integersOnly); helpers.extend(this,updatedRanges); },xLabels:标签,字体:helpers.fontString(this.options.scaleFontSize,this.options.scaleFontStyle,this.options.scaleFontFamily),lineWidth:this.options.scaleLineWidth,lineColor:this.options.scaleLineColor,showHorizo​​ntalLines:此.options.scaleShowHorizo​​ntalLines,showVerticalLines:this.options.scaleShowVerticalLines,gridLineWidth:(this.options.scaleShowGridLines)? this.options.scaleGridLineWidth:0,gridLineColor:(this.options.scaleShowGridLines)? this.options.scaleGridLineColor: rgba(0,0,0,0),填充:(this.options.showScale)吗? 0:this.options.pointDotRadius + this.options.pointDotStrokeWidth,showLabels:this.options.scaleShowLabels,显示:this.options.showScale}; if(this.options.scaleOverride){helpers.extend(scaleOptions,{calculateYRange:helpers.noop,step:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this。 options.scaleStartValue +(this.options.scaleSteps * this.options.scaleStepWidth)}); } this.scale = new Chart.CustomScale(scaleOptions); },}); //使用新的customYLabel optionChart.CustomScale = Chart.Scale.extend({draw:function(){var ctx = this.ctx,yLabelGap =(this.endPoint-this.startPoint)/ .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 *索引),linePositionY = Math.round(yLabelCenter),drawHorizo​​ntalLine = this.showHorizo​​ntalLines; ctx.textAlign = right; ctx.textBaseline = middle; if(this.showLabels) {// //如果我们有一个customYLabel,则使用它传递值x,y,画布和索引if(this.customYLabel){this.customYLabel(labelString,xStart-10,yLabelCenter,ctx,index); }其他{ctx.fillText(labelString,xStart-10,yLabelCenter); }} //这是X轴,因此如果(index === 0&&!drawHorizo​​ntalLine){drawHorizo​​ntalLine = true; }如果(drawHorizo​​ntalLine){ctx.beginPath(); } if(index> 0){//这是中心的网格线,因此删除ctx.lineWidth = this.gridLineWidth; ctx.strokeStyle = this.gridLineColor; } else {//这是刻度ctx.lineWidth = this.lineWidth;的第一行; ctx.strokeStyle = this.lineColor; } linePositionY + = helpers.aliasPixel(ctx.lineWidth);如果(drawHorizo​​ntalLine){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(); }, 这个); each(this.xLabels,function(label,index){var xPos = this.calculateX(index)+ aliasPixel(this.lineWidth),//检查此处是否有line / bar,并决定将linePos = this放置在哪里.calculateX(index-(this.offsetGridLines?0.5:0))+ aliasPixel(this.lineWidth),isRotated =(this.xLabelRotation> 0),drawVerticalLine = this.showVerticalLines; //这是Y轴,因此绘制它if(index === 0& amp;!drawVerticalLine){drawVerticalLine = true;} if(drawVerticalLine){ctx.beginPath();} if(index> 0){//这是中心的网格线,因此删除ctx.lineWidth = this.gridLineWidth; ctx.strokeStyle = this.gridLineColor;} else {//这是第一行比例ctx.lineWidth = this.lineWidth; ctx.strokeStyle = this.lineColor; }如果(drawVerticalLine){ctx.moveTo(linePos,this.endPoint); ctx.lineTo(linePos,this.startPoint-3); ctx.stroke(); ctx.closePath(); } ctx.lineWidth = this.lineWidth; ctx.strokeStyle = this.lineColor; //基本网格线底部的小行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.font = this.font; ctx.textAlign =(isRotated)吗?  right:中心; ctx.textBaseline =(isRotated)吗?  middle: top; ctx.fillText(label,0,0); ctx.restore(); }, 这个); }}}); var randomScalingFactor = function(){return Math.round(Math.random()* 100)}; //来自//https://www.designedbyaturtle.co.uk/2014/convert的示例颜色生成器-string-to-hexidecimal-color-with-javascript-vanilla ///将int转换为最大长度为六个字符的十六进制。var intToARGB = function(i){var h =(((i> 24)& 0xFF).toString(16)+((i> 16)& 0xFF).toString(16)+((i>> 8)& 0xFF).toString(16)+ (i& 0xFF).toString(16); return h.substring(0,6);} var lineChartData = {标签:[一月,二月,三月,四月,五月,六月,七月],数据集:[ {标签:我的第一个数据集,fillColor: rgba(220,220,220,1),strokeColor: rgba(220,220,220,1),pointColor: rgba(220,220,220,1),pointStrokeColor:#fff,pointHighlightFill :#fff,pointHighlightStroke: rgba(220,220,220,1),数据:[randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]},标签:我的第二个数据集,fillColor: rgba(151,187,205,0.2),strokeColor: rgba(151,187,205,1),pointColor: rgba(151,187,205,1),pointStrokeColor:#fff,pointHighlightFill:#fff ,pointHighlightStroke: rgba(151,187,205,1),数据:[null,10,null,null,60,null,null]}]} var ctx = document.getElementById( canvas)。getContext( 2d ); window.myLine = new Chart(ctx).LineAlt(lineChartData,{//使用示例,可​​以使用值代替索引customYLabel:函数(值,x,y,ctx,index){var defaultStyle = ctx.fillStyle ; ctx.fillStyle =‘#’+ intToARGB(index * 123456); ctx.fillText(value,x,y); ctx.fillStyle = defaultStyle; }});  

 < script src = https: //cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.js\"></script><div style = width:100%> < div> < canvas id = canvas height = 200 width = 600>< / canvas> < / div>< / div>  


I am using Chartjs to make line chart.
How can I change the y axis labels to colours? (i.e. red for 1, green for 2, black for 3, ..)

解决方案

UPDATE i've now added this feature into my fork of chartjs at https://github.com/leighquince/Chart.js, meanign you would not have to override or extend a new chart type. Just pass the option in like normal, here is an example http://fiddle.jshell.net/leighking2/jLzvhf4f/

So this could be achieved by overriding the scales draw method to run a custom function we provide when declaring the chart rather than just adding.

Below is the snippet but just as an explanation here is what has happened

  1. created a new chart and overridden the buildScale method to pass a new option called customYLabel. this will be the option you pass to your chart when you declare it and it has 4 parameters; the value of the label, x position, y position, the canvas, this index of the label

    1. the build scale also makes use of a custom scale
    2. create a custom scale which overrides the normal scales draw method to check for this customYLabel option and uses it if present

the reset is normal, what you customYLabel does is up to you but it should at the very least call `ctx.fillText(value,x,y) so that the label is drawn on the canvas. In the below example i colour the label based on it's index but the options there many.

(here is a fiddle as well if thats easier to view http://fiddle.jshell.net/leighking2/2cac5t34/)

//extract helpers so we can use them in our custom scale class
var helpers = Chart.helpers,
    each = helpers.each,
    aliasPixel = helpers.aliasPixel,
    toRadians = helpers.radians;

//new line chart which has an overridden buildscale that will pass the new option customYLabel
    Chart.types.Line.extend({
        // Passing in a name registers this chart in the Chart namespace in the same way
        name: "LineAlt",
        initialize: function (data) {
            Chart.types.Line.prototype.initialize.apply(this, arguments);
        },
        buildScale: function (labels) {
            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,
                fontStyle: this.options.scaleFontStyle,
                fontFamily: this.options.scaleFontFamily,
                valuesCount: labels.length,
                beginAtZero: this.options.scaleBeginAtZero,
                integersOnly: this.options.scaleIntegersOnly,
                //new options for custom y label
                customYLabel: this.options.customYLabel,
                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,
                showHorizontalLines: this.options.scaleShowHorizontalLines,
                showVerticalLines: this.options.scaleShowVerticalLines,
                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)
                });
            }


            this.scale = new Chart.CustomScale(scaleOptions);
        },

    });


//custom scale to use new customYLabel option
Chart.CustomScale = Chart.Scale.extend({
    draw: function () {
        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),
                    drawHorizontalLine = this.showHorizontalLines;

                ctx.textAlign = "right";
                ctx.textBaseline = "middle";
                if (this.showLabels) {
                    //if we have a customYLabel use it passing the value, x, y , canvas and index
                    if (this.customYLabel) {
                        this.customYLabel(labelString, xStart - 10, yLabelCenter, ctx, index);
                    } else {
                        ctx.fillText(labelString, xStart - 10, yLabelCenter);
                    }
                }

                // This is X axis, so draw it
                if (index === 0 && !drawHorizontalLine) {
                    drawHorizontalLine = true;
                }

                if (drawHorizontalLine) {
                    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);

                if (drawHorizontalLine) {
                    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) {
                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),
                    drawVerticalLine = this.showVerticalLines;

                // This is Y axis, so draw it
                if (index === 0 && !drawVerticalLine) {
                    drawVerticalLine = true;
                }

                if (drawVerticalLine) {
                    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;
                }

                if (drawVerticalLine) {
                    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.font = this.font;
                ctx.textAlign = (isRotated) ? "right" : "center";
                ctx.textBaseline = (isRotated) ? "middle" : "top";
                ctx.fillText(label, 0, 0);
                ctx.restore();
            }, this);

        }
    }
});











var randomScalingFactor = function () {
    return Math.round(Math.random() * 100)
};

//example colour generator from 
//https://www.designedbyaturtle.co.uk/2014/convert-string-to-hexidecimal-colour-with-javascript-vanilla/

// Convert an int to hexadecimal with a max length
// of six characters.
var intToARGB = function (i) {
    var h = ((i >> 24) & 0xFF).toString(16) + ((i >> 16) & 0xFF).toString(16) + ((i >> 8) & 0xFF).toString(16) + (i & 0xFF).toString(16);
    return h.substring(0, 6);
}
var lineChartData = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    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: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]

    }, {
        label: "My Second dataset",
        fillColor: "rgba(151,187,205,0.2)",
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        data: [null, 10, null, null, 60, null, null]

    }]

}


var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).LineAlt(lineChartData, {
    //example of how this can be used, could use the value instead of the index
    customYLabel: function (value, x, y, ctx, index) {
        var defaultStyle = ctx.fillStyle;
        ctx.fillStyle = '#' + intToARGB(index * 123456);
        ctx.fillText(value, x, y);
        ctx.fillStyle = defaultStyle;
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.js"></script>
<div style="width:100%">
    <div>
        <canvas id="canvas" height="200" width="600"></canvas>
    </div>
</div>

这篇关于如何更改Y轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆