var fireCtx = document.getElementById('fireNumberChart').getContext('2d');
var fireChart = new Chart(fireCtx, {
type: 'line',
data: {
labels: [], // Add your labels here
datasets: [{
label: 'Sensor Value',
data: [], // Add your sensor data here
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
suggestedMin: 0, // Ensure the y-axis starts at 0
beginAtZero: true,
precision: 0 // Display whole numbers only
}
}]
}
}
});
我想确保 y 轴上的最小数字始终固定为 0。这是我用于图表的 JavaScript 代码
const ctxWithoutNegativeValues = document.getElementById('chartWithoutNegativeValues');
const labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'];
const values = [12, 19, -3, 5, -2, -3];
const filterData = (labelArray, valuesArray) => {
const labels = [...labelArray]
const values = [...valuesArray]
const filteredLabels = [];
const filteredValues = valuesArray.filter((v,i) => {
const isPositiveValue = v > 0;
isPositiveValue && filteredLabels.push(labels[i]);
return isPositiveValue;
})
return [filteredLabels, filteredValues]
}
const [filteredLabels, filteredValues] = filterData(labels, values);
new Chart(ctxWithoutNegativeValues, {
type: 'bar',
data: {
labels: filteredLabels,
datasets: [{
label: 'Without(filtered) Negative Values',
data: filteredValues,
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
})
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div>
<canvas id="chartWithoutNegativeValues"></canvas>
</div>
您还可以隐藏负面数据
const ctxWithHiddenNegativeValues = document.getElementById('chartWithHiddenNegativeValues');
const labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'];
const values = [12, 19, -3, 5, -2, -3];
const filterData = (labelArray, valuesArray) => {
const labels = [...labelArray]
const values = [...valuesArray]
const hiddenLabels = [];
const hiddenValues = valuesArray.filter((v,i) => {
const isPositiveValue = v > 0;
hiddenLabels.push(labels[i]);
return isPositiveValue ? v : 0;
})
return [hiddenLabels, hiddenValues]
}
const [hiddenLabels, hiddenValues] = filterData(labels, values);
new Chart(ctxWithHiddenNegativeValues, {
type: 'bar',
data: {
labels: hiddenLabels,
datasets: [{
label: 'With Hidden Negative Values',
data: hiddenValues,
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
})
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div>
<canvas id="chartWithHiddenNegativeValues"></canvas>
</div>