1

如何为使用 chart.js 和 angular-chart.js 创建的折线图添加垂直轴(Y 轴)标签

我需要显示 y 轴标签。

HTML
<ion-content ng-controller="AgeController">
<canvas id="line" class="chart chart-line" data="data"
  labels="labels" legend="true" series="series"
  click="onClick" colours="['Red','Yellow']" width="402" height="201" style="width: 402px; height: 201px">
</canvas> 
</ion-content>

JS

app.controller('AgeController', ['$scope','$http',function($scope,$http) {    


           $scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
  $scope.series = ['Series A', 'Series B'];
  $scope.data = [
    [65, 59, 80, 81, 56, 55, 40],
    [28, 48, 40, 19, 86, 27, 90]
  ];


                }]);   
4

1 回答 1

4

关于轴标题的原始意见是在画布之外进行(请参见此处https://github.com/nnnick/Chart.js/issues/114),但鉴于链接问题上的活动https://github .com/nnnick/Chart.js/issues/52这可能会改变。


添加 Y 轴标题

也就是说,这里是您如何使用画布在当前版本上执行此操作的方法。首先,扩展图表以绘制轴标题(主要是如何使用希望更清晰的代码设置 ChartJS y 轴标题的重新散列)

Chart.types.Line.extend({
    name: "LineAlt",
    initialize: function (data) {
        // making space for the title by increasing the y axis label width
        if (this.options.yAxisLabel)
            this.options.scaleLabel = '         ' + this.options.scaleLabel;

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

        if (this.options.yAxisLabel)
            this.scale.yAxisLabel = this.options.yAxisLabel;
    },
    draw: function () {
        Chart.types.Line.prototype.draw.apply(this, arguments);

        // drawing the title
        if (this.scale.yAxisLabel) {
            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.scale.xScalePaddingLeft * 0.2;
            var y = this.chart.height / 2;
            // change origin
            ctx.translate(x, y)
            // rotate text
            ctx.rotate(-90 * Math.PI / 180);
            ctx.fillText(this.scale.yAxisLabel, 0, 0);
            ctx.restore();
        }
    }
});

根据您的指示,我假设您正在使用http://jtblin.github.io/angular-chart.js/。如果是这样,您可以像这样注册新的图表类型

angular.module('chart.js')
    .directive('chartLineAlt', ['ChartJsFactory', function (ChartJsFactory) { return new ChartJsFactory('LineAlt'); }]);

然后你使用这样的选项传入轴标题

...
$scope.options = {
    yAxisLabel: "My Y Axis Label",
}

带标记

<canvas id="line" class="chart chart-line-alt" data="data"
        labels="labels" legend="true" series="series" options="options"
        click="onClick" colours="['Red','Yellow']" width="402" height="201" style="width: 402px; height: 201px"></canvas>

注意添加options和更改的类chart-line-alt


小提琴 - http://jsfiddle.net/eeqfvy6f/

于 2015-08-21T11:30:12.950 回答