我有一个图表js条形图。它没有显示来自0的数据。如果具有值3和7,则图形将3作为y轴起点,将7作为最高轴。同样,如果我分别为5和8,则第一栏将变为空白,第二栏可见。
我添加了:
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
我的代码:
$(document).ready(function () {
showGraph();
});
function showGraph()
{
{
$.post("data.php",
function (data)
{
console.log(data);
var name = [];
var marks = [];
for (var i in data) {
name.push(data[i].label);
marks.push(data[i].y);
}
console.log(name);
console.log(marks);
var chartdata = {
labels: name,
datasets: [
{
label: 'Student Marks',
backgroundColor: '#49e2ff',
borderColor: '#46d5f1',
hoverBackgroundColor: '#CCCCCC',
hoverBorderColor: '#666666',
data: marks
}
]
};
var graphTarget = $("#graphCanvas");
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata
});
});
}
}
答案 0 :(得分:0)
尝试选项ticks.beginAtZero
,请参阅以下工作片段...
$(document).ready(function() {
var chartdata = {
labels: ['a', 'b'],
datasets: [{
label: 'Student Marks',
backgroundColor: '#49e2ff',
borderColor: '#46d5f1',
hoverBackgroundColor: '#CCCCCC',
hoverBorderColor: '#666666',
data: [3, 7]
}]
};
var graphTarget = $("#graphCanvas");
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<canvas id="graphCanvas"></canvas>