[英]How to set ChartJS Y axis title?
我正在使用Chartjs來顯示圖表,我需要設置 y 軸的標題,但文檔中沒有關於它的信息。
我需要像圖片一樣設置 y 軸,或者在 y 軸的頂部,這樣現在有人可以知道那個參數是什么
我看過官方網站,但沒有關於它的信息
在 Chart.js 2.0 版中,這是可能的:
options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
有關更多詳細信息,請參閱軸標簽文檔。
對於 Chart.js 2.x,請參閱 andyhasit 的回答 - https://stackoverflow.com/a/36954319/360067
對於 Chart.js 1.x,您可以調整選項並擴展圖表類型以執行此操作,如下所示
Chart.types.Line.extend({
name: "LineAlt",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
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.4;
var y = this.chart.height / 2;
// change origin
ctx.translate(x, y);
// rotate text
ctx.rotate(-90 * Math.PI / 180);
ctx.fillText(this.datasets[0].label, 0, 0);
ctx.restore();
}
});
像這樣稱呼它
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).LineAlt(data, {
// make enough space on the right side of the graph
scaleLabel: " <%=value%>"
});
注意標簽值前面的空格,這為我們提供了編寫 y 軸標簽的空間,而不會弄亂太多 Chart.js 內部結構
小提琴 - http://jsfiddle.net/wyox23ga/
對於 x 和 y 軸:
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'hola'
}
}],
}
}
chart.js 通過默認檢查鏈接支持這一點。 圖表
您可以在 options 屬性中設置標簽。
選項對象看起來像這樣。
options = {
scales: {
yAxes: [
{
id: 'y-axis-1',
display: true,
position: 'left',
ticks: {
callback: function(value, index, values) {
return value + "%";
}
},
scaleLabel:{
display: true,
labelString: 'Average Personal Income',
fontColor: "#546372"
}
}
]
}
};
對於 Chart.js 3.x
options: {
scales: {
y: {
title: {
display: true,
text: 'Y axis title'
}
}
}
}
對我來說,它是這樣工作的:
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
考慮在元素上使用 transform: rotate(-90deg) 樣式。 見http://www.w3schools.com/cssref/css3_pr_transform.asp
示例,在您的 css 中
.verticaltext_content {
position: relative;
transform: rotate(-90deg);
right:90px; //These three positions need adjusting
bottom:150px; //based on your actual chart size
width:200px;
}
向 Y 軸比例添加一個空間軟糖因子,以便文本有空間在您的 javascript 中呈現。
scaleLabel: " <%=value%>"
然后在圖表畫布后的 html 中放置類似...
<div class="text-center verticaltext_content">Y Axis Label</div>
這不是最優雅的解決方案,但是當我在 html 和圖表代碼之間有幾層時效果很好(使用 angular-chart 並且不想更改任何源代碼)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.