gpt4 book ai didi

javascript - 使用 chart.js 在折线图中显示垂直轴标签

转载 作者:行者123 更新时间:2023-11-30 10:00:15 27 4
gpt4 key购买 nike

如何为使用 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]
];


}]);

最佳答案

关于轴标题的原始意见是在 Canvas 之外进行(参见此处 https://github.com/nnnick/Chart.js/issues/114),但考虑到有关链接问题 https://github.com/nnnick/Chart.js/issues/52 的事件这可能会改变。


添加 Y 轴标题

就是说,这里是您可以使用 Canvas 在当前版本上执行此操作的方法。首先,扩展图表以绘制轴标题(主要是对 How to set ChartJS y axis title 的重新哈希处理,希望代码更清晰)

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>

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


fiddle - http://jsfiddle.net/eeqfvy6f/

关于javascript - 使用 chart.js 在折线图中显示垂直轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32102186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com