gpt4 book ai didi

javascript - 如何在 Chart.js 2 中为两个不同的条形图保留条形之间的间距

转载 作者:行者123 更新时间:2023-11-29 21:03:03 24 4
gpt4 key购买 nike

我有两个使用 Chart.js 的水平条形图,它们使用相同的选项对象,但数据量不同。有没有办法使底部(“位置”)图表在条形之间的边距方面看起来像顶部(“颜色”)?

Two horizontal bar charts with different spacing

我的选项对象如下所示,我很困惑:

      options={{
elements: {
rectangle: {
borderSkipped: 'left',
},
},
onClick: this.chartLink,
animation: false,
legend: {
display: false,
},
tooltips: {
enabled: false,
},
maintainAspectRatio: true,
scales: {
xAxes: [{
gridLines: {
display: false,
drawBorder: false,
},
ticks: {
beginAtZero: true,
display: false,
},
}],
yAxes: [{
tabIndex: 0,
maxBarThickness: 100,
categoryPercentage: 1.0,
barPercentage: 1.0,
barThickness: 20,
gridLines: {
display: false,
drawBorder: false,
},
ticks: {
fontColor: 'black',
fontStyle: 'normal',
maxTicksLimit: 5,
paddingLeft: 20,
mirror: true,
},
}],
},

最佳答案

您可以缩放第二个图表的高度以匹配两个图表中元素数量的比例。

Chart.js 需要 Canvas 周围有一个容器以允许动态调整大小,因此您还需要将其添加到 html 中。

我需要设置 maintainAspectRatio: false 才能正常工作

// scale second chart based on ratio of data to the first
var fiddleFactor = 1.05; // determined by guesswork. Basic ratio is slightly off.
var ratio = data2.labels.length * fiddleFactor / data1.labels.length;

var container1Height = parseInt(document.getElementById("container1").style.height);

// update height of second chart
document.getElementById("container2").style.height = container1Height * ratio + 'px';
<div id="container1" class="chart-container" style="position: relative; height:300px;">
<canvas id="myChart"></canvas>
</div>
<div id="container2" class="chart-container" style="position: relative; height:300px;">
<canvas id="myChart2"></canvas>
</div>

演示 http://plnkr.co/edit/LZMAtY0MOQpLunyGhpzH?p=preview

关于javascript - 如何在 Chart.js 2 中为两个不同的条形图保留条形之间的间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45516160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com