0๐
I added a ".slice(-4)" under the labels and data. and it did work! ๐ not sure if this is a solid way to do it but thanks @emilkarlsson
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Chart.js, the Missing Manual</title>
<style>
* {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.chartMenu {
width: 100vw;
height: 40px;
background: #1A1A1A;
color: rgba(75, 192, 192, 1);
}
.chartMenu p {
padding: 10px;
font-size: 20px;
}
.chartCard {
width: 100vw;
height: calc(100vh - 40px);
background: rgba(75, 192, 192, 0.2);
display: flex;
align-items: center;
justify-content: center;
}
.chartBox {
width: 700px;
padding: 20px;
border-radius: 20px;
border: solid 3px rgba(75, 192, 192, 1);
background: white;
}
</style>
</head>
<body>
<div class="chartMenu">
<p>Hi dear friend</p>
</div>
<div class="chartCard">
<div class="chartBox">
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.1.0/chartjs-plugin-datalabels.min.js" integrity="sha512-Tfw6etYMUhL4RTki37niav99C6OHwMDB2iBT5S5piyHO+ltK2YX8Hjy9TXxhE1Gm/TmAV0uaykSpnHKFIAif/A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
// data block
var week = [], kilometer = [], pushups = [], situps = []
async function dummyChart () {
await getDummyData()
const data = {
labels: week.slice(-4),
datasets: [{
label: 'Kilometer',
data: kilometer.slice(-4),
datalabels: {
anchor: 'end',
align: 'end',
offset: 5,
font: {
weight: 'bold'
}
},
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}
]
};
// config block
const config = {
type: 'line',
data: data,
options: {
scales: {
y: {
beginAtZero: true
}
}
},
plugins: [ChartDataLabels]
};
// init render block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
}
dummyChart()
// Fetch data from API
async function getDummyData() {
const apiUrl = "https://sheetdb.io/api/v1/an675a1pxghf6?sheet=Strava:weekly"
const response = await fetch(apiUrl)
const lineChartData = await response.json()
const weekdata = lineChartData.map( (x) => x.week)
const kilometerdata = lineChartData.map( (x) => x.kilometer)
const pushupsdata = lineChartData.map( (x) => x.pushups)
const situpsdata = lineChartData.map( (x) => x.situps)
console.log(kilometerdata, pushupsdata, situpsdata)
kilometer = kilometerdata
pushups = pushupsdata
situps = situpsdata
week = weekdata
}
</script>
</body>
</html>
Source:stackexchange.com