//编辑:添加了我的数据集并且没有弄清楚链接
我尝试构建堆积区域图表而不将我的数据集转换为百分比。最后的结果是,无论删除哪些数据集(单击图例时),图表上始终会显示100%。 here is what I am trying to emulate
我想我可能需要为此构建一个插件,但我不确定。以下是我的选择:
type: 'line',
data: {
labels: xAxis_label,
datasets: [{
label: "Dataset_1",
borderColor: "yellow",
backgroundColor: "yellow",
data: [60, 45, 82, 100, 12, 22, 45, 56]
}, {
label: "Dataset_2",
borderColor: "blue",
backgroundColor: "blue",
data: [15, 217, 8, 219, 4, 16, 115, 9]
},{
label: "Dataset_3",
borderColor: "green",
backgroundColor: "green",
data: [840, 750, 910, 874, 799, 610, 612, 839]
}, {
label: "Dataset_4",
borderColor: "grey",
backgroundColor: "grey",
data: [15, 22, 5, 17, 32, 40, 44, 8]
}]
},
options: {
responsive: true,
title:{
display:true,
text:"sugar honey iced tea"
},
tooltips: {
mode: 'index'
},
hover: {
mode: 'index'
},
scales: {
xAxes: [{
gridLines: {
display: false
},
scaleLabel: {
display: true,
labelString: 'Time'
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
min: 0,
max: 100,
callback: function(value){return value+ "%";}
},
stacked: true,
scaleLabel: {
display: true,
labelString: 'Percentage'
}
}]
}
}
};
答案 0 :(得分:1)
你确实需要构建一个插件来实现类似的东西。
这是我构建的一个插件,可以完成工作......
Chart.plugins.register({
beforeDraw: function(c) {
let ticks = c.scales['y-axis-0'].ticks;
let step = 100 / (ticks.length - 1);
let tick = 0;
ticks.forEach((e, i, a) => {
let index = a.length - 1 - i;
a[index] = (tick | 0) + '%';
tick += step;
});
}
});
注意:
您还需要为y轴添加以下选项...
afterFit: function(e) {
e.width = 60
}
这是为了调整图表的大小,以便y轴刻度适合视图。
ᴡᴏʀᴋɪɴɢᴡᴏʀᴋɪɴɢxᴀᴍᴘʟᴇᴀᴍᴘʟᴇ
Chart.plugins.register({
beforeDraw: function(c) {
let ticks = c.scales['y-axis-0'].ticks;
let step = 100 / (ticks.length - 1);
let tick = 0;
ticks.forEach((e, i, a) => {
let index = a.length - 1 - i;
a[index] = (tick | 0) + '%';
tick += step;
});
}
});
var chartData = {
labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
datasets: [{
label: "Dataset_1",
borderColor: "yellow",
backgroundColor: "yellow",
data: [60, 45, 82, 100, 12, 22, 45, 56]
}, {
label: "Dataset_2",
borderColor: "blue",
backgroundColor: "blue",
data: [15, 217, 8, 219, 4, 16, 115, 9]
}, {
label: "Dataset_3",
borderColor: "green",
backgroundColor: "green",
data: [840, 750, 910, 874, 799, 610, 612, 839]
}, {
label: "Dataset_4",
borderColor: "grey",
backgroundColor: "grey",
data: [15, 22, 5, 17, 32, 40, 44, 8]
}]
};
var canvas = document.getElementById('canvas');
var myBarChart = new Chart(canvas, {
type: "line",
data: chartData,
options: {
responsive: true,
title: {
display: true,
text: "sugar honey iced tea"
},
tooltips: {
mode: 'label'
},
scales: {
xAxes: [{
gridLines: {
display: false
},
scaleLabel: {
display: true,
labelString: 'Time'
}
}],
yAxes: [{
afterFit: function(e) {
e.width = 60 //set that suits the best
},
stacked: true,
scaleLabel: {
display: true,
labelString: 'Percentage'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>