我的条形图中有一个时间轴x和当天2017-10-09
的单个值。
我希望图表的宽度为31条(本月为31天),但由于我只有一个值,因此chartjs将宽度计算为1 bar。
var ctx = document.getElementById("myChart");
var data = JSON.parse('{"first":[{"x":"2017-10-09","y":107}]}');
new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
backgroundColor: "rgba(0,120,200,0.4)",
data: data.first,
label: 'First',
}]
},
options: {
hover: {
mode: null
},
legend: {
display: false,
},
maintainAspectRatio: false,
responsive: true,
scales: {
xAxes: [{
bounds: 'ticks',
time: {
displayFormats: {
month: 'MMM YY',
day: 'D'
},
unit: 'month'
},
type: 'time'
}],
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
return (value % 1 === 0) ? value : null;
}
}
}]
},
tooltips: {
enabled: false
}
}
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
&#13;
这里是fiddle。
我怎样才能做到这一点?
答案 0 :(得分:0)
就像我在评论中提到的那样:并不是说你的x轴宽度不对,而是条形本身:
我添加了<pre id="out"></pre>
来设置条形图的宽度,现在它只显示在特定日期
barThickness: 10
&#13;
var ctx = document.getElementById("myChart");
var data = JSON.parse('{"first":[{"x":"2017-10-09","y":107}]}');
new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
backgroundColor: "rgba(0,120,200,0.4)",
data: data.first,
label: 'First',
}]
},
options: {
hover: {
mode: null
},
legend: {
display: false,
},
maintainAspectRatio: false,
responsive: true,
scales: {
xAxes: [{
bounds: 'ticks',
categoryPercentage: 1,
barPercentage: .1,
time: {
displayFormats: {
month: 'MMM YY',
day: 'D'
},
unit: 'month'
},
type: 'time'
}],
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
return (value % 1 === 0) ? value : null;
}
}
}]
},
tooltips: {
enabled: false
}
}
});
&#13;
这是一个包含更多值的代码段:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
&#13;
var ctx = document.getElementById("myChart");
var width = ctx.width/31;
var data = JSON.parse('{"first":[{"x":"2017-10-05","y":107},{"x":"2017-10-09","y":107},{"x":"2017-10-15","y":107},{"x":"2017-10-31","y":107}]}');
new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
backgroundColor: "rgba(0,120,200,0.4)",
data: data.first,
label: 'First',
}]
},
options: {
hover: {
mode: null
},
legend: {
display: false,
},
maintainAspectRatio: false,
responsive: true,
scales: {
xAxes: [{
bounds: 'ticks',
barThickness: width,
time: {
displayFormats: {
month: 'MMM YY',
day: 'D'
},
unit: 'month'
},
type: 'time'
}],
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
return (value % 1 === 0) ? value : null;
}
}
}]
},
tooltips: {
enabled: false
}
}
});
&#13;