图表Js在线图的x轴上更改标签方向 [英] Chart Js Change Label orientation on x-Axis for Line Charts

查看:70
本文介绍了图表Js在线图的x轴上更改标签方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用



有人可以帮我调整旋转标签的条形图解决方案,以便我可以在折线图上使用它吗?

解决方案

使用与上一个答案相同的方法,唯一需要改变的是图表类型的扩展。这次是扩展折线图,并且设置稍有不同,因为折线图比例是在构建比例中创建的,所以这次是 buildScale 被覆盖所以使用自定义比例并且可以传入新选项 overrideRotation initialize 也被覆盖,但仅限于此可以调用super initialize并在构建图形时滚动。



  var helpers = Chart.helpers; Chart.MyScale = Chart。 Scale.extend({calculateXLabelRotation:function(){//通过计算0和1之间x偏移之间的差值来获取每个网格的宽度.his.ctx.font = this.font; var firstWidth = this.ctx。 measureText(this.xLabels [0])。width,lastWidth = this.ctx.measureText(this.xLabels [this.xLabels.length  -  1])。width,firstRotated, lastRotated; this.xScalePaddingRight = lastWidth / 2 + 3; this.xScalePaddingLeft =(firstWidth / 2> this.yLabelWidth + 10)? firstWidth / 2:this.yLabelWidth + 10; this.xLabelRotation = 0; if(this.display){var originalLabelWidth = helpers.longestText(this.ctx,this.font,this.xLabels),cosRotation,firstRotatedWidth; this.xLabelWidth = originalLabelWidth; //允许3像素x2填充任一侧的标签可读性var xGridWidth = Math.floor(this.calculateX(1) -  this.calculateX(0)) -  6; if(this.overrideRotation){this.xLabelRotation = this.overrideRotation; cosRotation = Math.cos(helpers.radians(this.xLabelRotation)); //我们现在正确地调整文本。 if(firstRotated + this.fontSize / 2> this.yLabelWidth + 8){this.xScalePaddingLeft = firstRotated + this.fontSize / 2; } this.xScalePaddingRight = this.fontSize / 2; this.xLabelWidth = cosRotation * originalLabelWidth; } else {//最大标签旋转应为90  - 同时充当循环计数器((this.xLabelWidth> xGridWidth&& this.xLabelRotation === 0)||(this.xLabelWidth> xGridWidth& & this.xLabelRotation< = 90&& this.xLabelRotation> 0)){cosRotation = Math.cos(helpers.radians(this.xLabelRotation)); firstRotated = cosRotation * firstWidth; lastRotated = cosRotation * lastWidth; //我们现在正确地调整文本。 if(firstRotated + this.fontSize / 2> this.yLabelWidth + 8){this.xScalePaddingLeft = firstRotated + this.fontSize / 2; } this.xScalePaddingRight = this.fontSize / 2; this.xLabelRotation ++; this.xLabelWidth = cosRotation * originalLabelWidth; if(this.xLabelRotation> 0){this.endPoint  -  = Math.sin(helpers.radians(this.xLabelRotation))* originalLabelWidth + 3; }} else {this.xLabelWidth = 0; this.xScalePaddingRight = this.padding; this.xScalePaddingLeft = this.padding; Chart.types.Line.extend({name:MyLine,initialize:function(data){Chart.types.Line.prototype.initialize.apply(this,arguments);},buildScale:function (标签){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,offsetGridLines:this.options.offsetGridLines, fontSize:this.options.scaleFontSize,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(d ataTotal(),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,showHorizo​​ntalLines:this .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,display:this.options.showScale,overrideRotation:this.options.overrideRotation,}; 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.MyScale(scaleOptions); },}); var randomScalingFactor = function(){return Math.round(Math.random()* 100)}; var barChartData = {labels:[January,February,March,April, May,June,July],数据集:[{fillColor:rgba(20,20,220,0.2),strokeColor:rgba(20,20,220,1),pointColor:rgba(20, 20,220,1),pointStrokeColor:#ftf,pointHighlightFill:#iff,pointHighlightStroke:rgba(20,20,220,1),数据:[randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor( ),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]},{fillColor:rgba(120,120,120,0.2),strokeColor:rgba(120,220,120,1),pointColor:rgba(120,120,120,1), pointStrokeColor:#ftf,pointHighlightFill:#fff,pointHighlightStroke:rgba(120,120,120,1),data:[randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor( ),randomScalingFactor()]},{fillColo r: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(),randomScalingFactor()]}]} window.onload = function(){ var ctx = document.getElementById(canvas)。getContext(2d); window.myBar = new Chart(ctx).MyLine(barChartData,{overrideRotation:90});}  

 < script src =http://www.chartjs.org/assets/Chart.min.js>< / script>< canvas id =canvasheight =150width =300>< / canvas>  


I am using chart.js.

Similar to this Question, I would like to rotate my x-axis labels 90 degrees. Currently my labels are rotated about 80 degrees with default settings.

Could somebody help me adapt the bar-chart solution for rotating labels, so that I can use it on line-charts?

解决方案

Using the same method as in the previous answer the only thing that needs to changed is the extension of the graph type. This time it is extending the line chart and the set-up is a little different as the Line charts scale is created in the build scale so this time it is buildScale is overridden so that the custom scale is used and the new option overrideRotation can be passed in. initialize is also overridden but only so that the super initialize can be called and get the ball rolling on building the graph.

var helpers = Chart.helpers;
Chart.MyScale = Chart.Scale.extend({
  calculateXLabelRotation: function() {
    //Get the width of each grid by calculating the difference
    //between x offsets between 0 and 1.

    this.ctx.font = this.font;

    var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
      lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
      firstRotated,
      lastRotated;


    this.xScalePaddingRight = lastWidth / 2 + 3;
    this.xScalePaddingLeft = (firstWidth / 2 > this.yLabelWidth + 10) ? firstWidth / 2 : this.yLabelWidth + 10;

    this.xLabelRotation = 0;
    if (this.display) {
      var originalLabelWidth = helpers.longestText(this.ctx, this.font, this.xLabels),
        cosRotation,
        firstRotatedWidth;
      this.xLabelWidth = originalLabelWidth;
      //Allow 3 pixels x2 padding either side for label readability
      var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;

      if (this.overrideRotation) {
        this.xLabelRotation = this.overrideRotation;
        cosRotation = Math.cos(helpers.radians(this.xLabelRotation));
        // We're right aligning the text now.
        if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8) {
          this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
        }
        this.xScalePaddingRight = this.fontSize / 2;
        this.xLabelWidth = cosRotation * originalLabelWidth;
      } else {
        //Max label rotate should be 90 - also act as a loop counter
        while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)) {
          cosRotation = Math.cos(helpers.radians(this.xLabelRotation));

          firstRotated = cosRotation * firstWidth;
          lastRotated = cosRotation * lastWidth;

          // We're right aligning the text now.
          if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8) {
            this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
          }
          this.xScalePaddingRight = this.fontSize / 2;


          this.xLabelRotation++;
          this.xLabelWidth = cosRotation * originalLabelWidth;

        }
      }
      if (this.xLabelRotation > 0) {
        this.endPoint -= Math.sin(helpers.radians(this.xLabelRotation)) * originalLabelWidth + 3;
      }
    } else {
      this.xLabelWidth = 0;
      this.xScalePaddingRight = this.padding;
      this.xScalePaddingLeft = this.padding;
    }

  },

});

Chart.types.Line.extend({
  name: "MyLine",
  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,
      offsetGridLines: this.options.offsetGridLines,
      fontSize: this.options.scaleFontSize,
      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,
      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,
      overrideRotation: this.options.overrideRotation,
    };

    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.MyScale(scaleOptions);
  },
});



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

var barChartData = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    fillColor: "rgba(20,20,220,0.2)",
    strokeColor: "rgba(20,20,220,1)",
    pointColor: "rgba(20,20,220,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(20,20,220,1)",
    data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
  }, {
    fillColor: "rgba(120,120,120,0.2)",
    strokeColor: "rgba(120,220,120,1)",
    pointColor: "rgba(120,120,120,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(120,120,120,1)",
    data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
  }, {
    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(), randomScalingFactor()]
  }]

}
window.onload = function() {
  var ctx = document.getElementById("canvas").getContext("2d");
  window.myBar = new Chart(ctx).MyLine(barChartData, {
    overrideRotation: 90
  });
}

<script src="http://www.chartjs.org/assets/Chart.min.js"></script>

<canvas id="canvas" height="150" width="300"></canvas>

这篇关于图表Js在线图的x轴上更改标签方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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