折れ線グラフも棒グラフも自由自在!
chart.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'horizontalBar', //bar 棒グラフ、line 折れ線グラフ、horizontalBar 横の棒グラフ
// The data for our dataset
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [{
label: '@NJ',
data: [80, 50, 60, 40, 30, 150],
backgroundColor: 'skyblue',
borderColor: 'blue',
borderWidth: 0,
fill: false,
pointStyle: 'rect'
},{
label: '@haruka',
data: [100, 100, 40, 50, 30, 100],
// borderColor: 'blue',
// borderWidth: 5,
backgroundColor: [
'hsla(90, 60%, 60%, 0.3)',
'hsla(180, 60%, 60%, 0.3)',
'hsla(270, 60%, 60%, 0.3)',
'hsla(360, 60%, 60%, 0.3)',
'hsla(0, 60%, 60%, 0.3)',
'hsla(80, 60%, 60%, 0.3)',
],
lineTension: 0,
pointStyle: 'triangle'
}]
},
// Configuration options go here
options: {
// scales: {
// yAxes: [{
// ticks: {
// // min: 0,
// // max:100
// suggestedMin: 0,
// suggestedMax: 100,
// stepSize: 10,
// callback: function(value, index, values){
// return 'JPY'+ value;
// }
// }
// }]
// },
//積み上げ棒グラフ
scales:{
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
},
title: {
display: true,
text: 'Annual Sales',
fontSize: 18,
position:'left'
},
animation: {
duration: 0
},
legend:{
// position: 'right'
// display: false
}
}
});
var myLineChart = new Chart(ctx, {
type: type,
data: data,
options: options
});
</script>
</body>
</html>
結果は以下の図の通り。最初は折れ線グラフで作ったり枠の色変えたり
縦の棒グラフ作ってたりしたから不要なコードも沢山あります。
(//でコメントにしてるよ)
折れ線グラフ
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>my Chart</title>
</head>
<body>
<canvas id ="my_chart">
Canvas not supported...
</canvas>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script>
'use strict';
var type = 'line';
var data = {
labels: [2010, 2011, 2012, 2013],
datasets: [{
label: '@haruka',
data: [120, 130, 140, 150]
}, {
label: '@koji',
data: [180, 200, 150, 300]
}]
};
var options;
var ctx = document.getElementById('my_chart').getContext('2d');
var myChart = new Chart(ctx, {
type: type,
data: data,
options: options
});
</script>
</body>
</html>