我使用chart.js创建了一个折线图,我希望第二个y轴(MinutesofUsage)显示在图表的右侧(第二轴)。
这是显示图形的代码部分。
<script>
var data = <?php echo json_encode($data); ?>;
var callTypes = <?php echo json_encode(array_unique(array_column($data, "callType"))); ?>;
// Function to create a chart with dynamic Y-axis scales
function createChartWithYAxis(index) {
if (index < callTypes.length) {
var callType = callTypes[index];
var chartContainer = document.createElement('div');
chartContainer.className = 'chart-container';
// Add the chart name
var chartTitle = document.createElement('div');
chartTitle.innerText = 'Chart: ' + callType;
chartContainer.appendChild(chartTitle);
var ctx = document.createElement('canvas').getContext('2d');
ctx.canvas.id = callType + 'Chart';
ctx.canvas.style.display = 'block';
chartContainer.appendChild(ctx.canvas);
document.body.appendChild(chartContainer);
var filteredData = data.filter(function (item) {
return item.callType === callType;
});
var dates = filteredData.map(function (item) {
return item.date;
});
var revenues = filteredData.map(function (item) {
return item.revenue;
});
var minutesUsage = filteredData.map(function (item) {
return item.minutesUsage;
});
new Chart(ctx, {
type: 'line',
data: {
labels: dates,
datasets: [
{
label: 'Minutes Usage',
data: minutesUsage,
borderColor: 'green',
borderWidth: 2,
fill: false,
yAxisID: 'minutes-axis'
},
{
label: 'Total Revenue',
data: revenues,
borderColor: 'blue',
borderWidth: 2,
fill: false,
yAxisID: 'revenue-axis'
}
]
},
options: {
responsive: true,
layout: {
padding: {
left: 5,
right: 5
}
},
scales: {
x: [{
type: 'time',
time: {
unit: 'day'
},
title: {
display: true,
text: 'Date'
}
}],
y: [
{
id: 'revenue-axis',
position: 'left', //position of the y-axis(revenue-axis)
title: {
display: true,
text: 'Total Revenue',
fontColor: 'blue' // Set the color for the revenue y-axis label
},
ticks: {
fontColor: 'blue' // Set the color for the revenue y-axis ticks
}
},
{
id: 'minutes-axis',
position: 'right', //position of the y-axis(minutesofusage-axis)
title: {
display: true,
text: 'Minutes Usage',
fontColor: 'green' // Set the color for the minutes y-axis label
},
ticks: {
fontColor: 'green' // Set the color for the minutes y-axis ticks
}
}
]
},
plugins: {
datalabels: {
display: 'auto',
color: 'black',
}
}
}
});
// Smooth scroll to the newly created chart
chartContainer.scrollIntoView({ behavior: 'smooth' });
} else {
clearInterval(chartInterval); // Stop the slideshow
}
}
var currentIndex = 0;
var chartInterval = setInterval(function() {
createChartWithYAxis(currentIndex);
currentIndex++;
}, 5000); // Delay between chart displays (in milliseconds)
</script>
字符串
我尝试将位置属性更改为right,但图表没有任何变化。
1条答案
按热度按时间92dk7w1h1#
根据您使用的Chart.js版本,
chart.options.scales.x
和chart.options.scales.y
不应该是数组。您应该在chart.options.scales
中的每个轴上有一个对象,例如:个字符