我制作了两个图表,一个折线图和一个条形图,您可以在两个图表之间进行切换,并且这些图表包含不同的数据。问题是我似乎无法使它们从零开始?我将代码放在脚本的何处,所以两个图表都从零开始,因为现在它不起作用,或者整个条形都消失了。
<script>
let lineConfig = {
type: 'line',
data: {
labels: ["2012", "2013", "2014", "2015", "2016", "2017"],
datasets: [{
label: "Miljoner ton",
data: [56.38, 59.3, 61.81, 58.83, 52.32, 66.86],
lineTension: 0.1,
backgroundColor: "rgba(0,255,0,0.4)",
borderColor: "green", // The main line color
borderCapStyle: 'square',
pointBorderColor: "white",
pointBackgroundColor: "green",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "green",
pointHoverBorderWidth: 2,
pointRadius: 4,
}]
}
},
barConfig = {
type: 'bar',
data: {
labels: ['Palmolja', "Sojaolja", 'Animaliskt fett', 'Solrosolja', 'Rapsolja', 'Annat'],
datasets: [{
label: "Procent",
data: [28.6, 25.3, 13.2, 8.0, 12.2, 9.6],
backgroundColor: "rgba(0,255,0,0.4)",
borderColor: "green", // The main line color
borderCapStyle: 'square',
pointBorderColor: "white",
pointBackgroundColor: "green",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "green",
pointHoverBorderWidth: 2,
pointRadius: 4,
}]
}
},
activeType = 'bar', // we'll start with a bar chart.
myChart;
function init(config) {
// create a new chart with the supplied config.
myChart = new Chart(document.getElementById('chart'), config);
}
// first init as a bar chart.
init(barConfig);
document.getElementById('switch').addEventListener('click', function(e) {
// every time the button is clicked we destroy the existing chart.
myChart.destroy();
if (activeType == 'bar') {
// chart was a bar, init a new line chart.
activeType = 'line';
init(lineConfig);
return;
}
// chart was a line, init a new bar chart.
activeType = 'bar';
init(barConfig);
});
</script>
答案 0 :(得分:2)
假设您的意思是线性y轴,那么documentation指定以下内容:
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
根据OP comment进行编辑:
options
属性是type
和data
的兄弟姐妹,例如:
{
type: 'line',
data: {
labels: [...],
datasets: [{
data: [...]
}]
},
options: {
...
}
}