我正在尝试将条形图安装到父容器中,但是容器的左侧和右侧之间有一个间隙(请参见示例),或者,如果偏移量为false,则第一个和最后一个条仅是容器的一半。所有其他条的宽度...如何解决?
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: ['one','two','three','four','five'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [100, 90, 80, 90, 100],
}]
},
// Configuration options go here
options: {
legend:{display:false},
scales: {
xAxes: [
{
display: false,
offset: true,
},
],
yAxes: [
{
display: false,
offset: false,
ticks: {
beginAtZero: true
}
},
],
},
}
});
div {
width:400px;
height:200px;
border:1px solid black;
padding:0;
margin:0
}
#myChart {
padding:0;
margin:0;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div>
<canvas id="myChart"></canvas>
</div>
您可以通过使用数据集上的borderWidth
选项分别为每个条定义左右不可见边框来实现此目的。同时,您需要在数据集上定义borderWidth
和categoryPercentage: 1
(请参见barPercentage: 1
)。
在下面的代码示例中,计算出的Dataset Configuration产生以下数组:
borderWidths
如果要更改条形之间的间距,请更改变量[
{
"left": 0,
"right": 20
},
{
"left": 5,
"right": 15
},
{
"left": 10,
"right": 10
},
{
"left": 15,
"right": 5
},
{
"left": 20,
"right": 0
}
]
的值。
factor
var labels = ['one', 'two', 'three', 'four', 'five'];
var borderWidths = [];
var factor = 5;
for (let i = 0; i < labels.length; i++) {
borderWidths.push({ left: i * factor, right: (labels.length - 1 - i) * factor });
}
var chart = new Chart(document.getElementById('myChart'), {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
data: [100, 90, 80, 90, 100],
categoryPercentage: 1,
barPercentage: 1,
borderWidth: borderWidths,
borderColor: 'white',
hoverBorderColor: 'white'
}]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false,
ticks: {
beginAtZero: true
}
}],
}
}
});
#div_chart {
width:400px;
height:200px;
border:1px solid black;
padding:0;
margin:0
}
#myChart {
padding:0;
margin:0;
}