<!DOCTYPE html>
<html>
<head>
<title>Chart Example</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="myChart" width="800" height="400"></canvas>
<?php
// Data
$yy_values = array('$yy', '$yy1', '$yy3', '$yy6');
$yy_counts = array(20, 240, 60, 40);
$age = 30;
// Create chart data
$data = array();
for ($i = 0; $i < count($yy_values); $i++) {
$yy = $yy_values[$i];
$count = $yy_counts[$i];
$cumulative_count = 0;
$data[$yy] = array();
for ($j = 0; $j <= $count; $j++) {
$cumulative_count += 1;
array_push($data[$yy], $cumulative_count);
}
}
// Create X-axis labels
$labels = array();
for ($i = $age; $i <= 100; $i += 5) {
array_push($labels, $i);
}
?>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: <?php echo json_encode($labels); ?>,
datasets: [
{
label: '$yy',
data: <?php echo json_encode($data['$yy']); ?>,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1,
pointRadius: 0
},
{
label: '$yy1',
data: <?php echo json_encode($data['$yy1']); ?>,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1,
pointRadius: 0
},
{
label: '$yy3',
data: <?php echo json_encode($data['$yy3']); ?>,
backgroundColor: 'rgba(255, 206, 86, 0.2)',
borderColor: 'rgba(255, 206, 86, 1)',
borderWidth: 1,
pointRadius: 0
},
{
label: '$yy6',
data: <?php echo json_encode($data['$yy6']); ?>,
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1,
pointRadius: 0
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
max: 10000000,
min: 0,
stepSize: 1000000
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Age'
},
ticks: {
min: <?php echo $age; ?>,
max: 100,
stepSize: 5
}
}]
}
}
});
</script>
</body>
</html>
แบบ2
<!DOCTYPE html>
<html>
<head>
<title>Chart Example</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div style="width: 600px;">
<canvas id="myChart"></canvas>
</div>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var data = {
labels: ['$yy', '$yy1', '$yy3', '$yy6'],
datasets: [{
label: '$xx',
data: [
20, // $yy
240, // $yy1
60, // $yy3
40 // $yy6
],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
};
var options = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
max: 10000000,
stepSize: 1000000,
callback: function(value, index, values) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
}
}],
xAxes: [{
ticks: {
callback: function(value, index, values) {
var age = parseInt('<?php echo $age; ?>');
return '$' + (age + parseInt(value)).toString();
}
}
}]
},
title: {
display: true,
text: 'Chart Title'
}
};
var chart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
</script>
</body>
</html>