Chart.js - Weekly bar chart example
by Hugo Carneiro
HTML
<script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<div class="graph-holder">
<canvas id="myChart"></canvas>
</div>
CSS
.graph-holder {
position: relative;
width: 100%;
height: 500px;
}
JavaScript
const data = [{
x: Date.parse('2022-08-30'),
y: 10
}, {
x: Date.parse('2022-08-31'),
y: 6
}, {
x: Date.parse('2022-09-02'),
y: 56
}, {
x: Date.parse('2022-09-03'),
y: 12
}, {
x: Date.parse('2022-09-04'),
y: 1
}];
// Data setup
const dataSet = {
datasets: [{
label: "My dataset label",
data,
datalabels: {
color: '#FFCE56'
},
backgroundColor: 'rgba(71, 73, 117, 1)'
}]
};
// config
const chartConfig = {
type: 'bar',
plugins: [ChartDataLabels],
data: dataSet,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
},
datalabels: {
anchor: 'end',
align: 'start',
labels: {
value: {
color: '#ffffff'
}
},
formatter: function(value, ctx) {
return value.y;
}
},
tooltip: {
callbacks: {
title: function(context) {
return moment(context[0].parsed.x).format('dddd');
}
}
}
},
scales: {
x: {
type: 'time',
min: Date.parse('2022-08-29'),
max: Date.parse('2022-09-04'),
time: {
unit: 'day',
displayFormats: {
day: 'ddd'
},
round: 'day',
isoWeekday: 1
}
},
y: {
beginAtZero: true
}
}
}
};
var ctx = document.getElementById('myChart').getContext('2d');
var myChart1 = new Chart(ctx, chartConfig);