折線圖是排列在工作表的列或行中的資料可以繪制到折線圖中。
折線圖可以顯示随時間(根據常用比例設定)而變化的連續資料,是以非常适用于顯示在相等時間間隔下資料的趨勢。
折線圖 type 屬性為 line ,type 描述了圖表類型。
const config = {
type: 'line',
data: data,
};
接下來我們建立一個簡單的折線圖:
執行個體
const ctx = document.getElementById('myChart');
const labels = ['一月份', '二月份', '三月份','四月份', '五月份', '六月份', '七月份']; // 設定 X 軸上對應的标簽
const data = {
labels: labels,
datasets: [{
label: '我的第一個折線圖',
data: [65, 59, 80, 81, 56, 55, 40],
fill: false,
borderColor: 'rgb(75, 192, 192)', // 設定線的顔色
tension: 0.1
}]
};
const config = {
type: 'line', // 設定圖表類型
data: data,
};
const myChart = new Chart(ctx, config);
以上執行個體輸出結果為:
接下來我們豐富一下折線圖,添加選項,設定如下:
執行個體
const ctx = document.getElementById('myChart');
const labels = ['一月份', '二月份', '三月份','四月份', '五月份', '六月份', '七月份']; // 設定 X 軸上對應的标簽
const data = {
labels: labels,
datasets: [{
label: '我的第一個折線圖',
data: [65, 59, 80, 81, 56, 55, 40],
fill: false,
borderColor: 'rgb(75, 192, 192)', // 設定線的顔色
backgroundColor: ['rgba(179, 0, 33, 0.5)'],// 設定點的填充色
pointStyle: 'circle', //設定點類型為圓點
pointRadius: 6, //設定圓點半徑
pointHoverRadius: 10, //設定滑鼠移動上去後圓點半徑
tension: 0.1
}]
};
const config = {
type: 'line', // 設定圖表類型
data: data,
options: {
responsive: true, // 設定圖表為響應式
interaction: { // 設定每個點的互動
intersect: false,
},
scales: { // 設定 X 軸與 Y 軸
x: {
display: true,
title: {
display: true,
text: '日期'
}
},
y: {
display: true,
title: {
display: true,
text: '票數'
}
}
}
}
};
const myChart = new Chart(ctx, config);
以上執行個體輸出結果為:
垂直折線圖
垂直折線圖是水準折線圖的變體。
垂直折線圖需要将選項對象中的 indexAxis 屬性設定為 y,indexAxis 屬性的預設值為 x。
執行個體
const ctx = document.getElementById('myChart');
const labels = ['一月份', '二月份', '三月份','四月份', '五月份', '六月份', '七月份']; // 設定 X 軸上對應的标簽
const data = {
labels: labels,
datasets: [{
label: '我的第一個折線圖',
data: [65, 59, 80, 81, 56, 55, 40],
fill: false,
borderColor: 'rgb(75, 192, 192)', // 設定線的顔色
backgroundColor: ['rgba(179, 0, 33, 0.5)'],// 設定點的填充色
pointStyle: 'circle', //設定點類型為圓點
pointRadius: 6, //設定圓點半徑
pointHoverRadius: 10, //設定滑鼠移動上去後圓點半徑
tension: 0.1
}]
};
const config = {
type: 'line', // 設定圖表類型
data: data,
options: {
indexAxis: 'y', // 設定垂直折線圖
responsive: true, // 設定圖表為響應式
interaction: { // 設定每個點的互動
intersect: false,
},
scales: { // 設定 X 軸與 Y 軸
x: {
beginAtZero: true,// 設定 X 軸從 0 開始
display: true,
title: {
display: true,
text: '日期'
}
},
y: {
display: true,
title: {
display: true,
text: '票數'
}
}
}
}
};
const myChart = new Chart(ctx, config);
以上執行個體輸出結果為: