javascript - 使用 chart.js 创建条形图,其中每个条形的空间相同,调整了整体图表大小
问题描述
这是我的 Javascript 选项和两个显示我创建的图表示例的屏幕截图。条的宽度设置为 50 像素。但是图表的整体大小是相同的,即使一张图表有两个条形图,而另外五个。这意味着有五个条的图表比有两个条的图表更紧,即使实际的条都是 50 像素。我正在寻找这两个图表之间的更多一致性,以便只有两个条形图的图表总体上会是一个“更短”的图表,其间距与具有五个条形图的图表相匹配。用chart.js可以吗?
options: {
aspectRatio: 3,
legend: {
display: false
},
scales: {
xAxes: [{
barThickness: 50,
ticks: {
beginAtZero: true,
suggestedMax: maxAxisX
}
}],
yAxes: [{
maxBarThickness: 50,
ticks: {
beginAtZero: true
}
}]
}
}
解决方案
插件核心 API提供了一系列可用于执行自定义代码的钩子。您可以使用挂钩来根据图表中包含的条数来定义父beforeRender
级的高度。此函数还必须考虑图表顶部和下方所需的空间,尤其是在绘制 xAxis 刻度时。canvas
div
plugins: [{
beforeRender: chart => {
if (!chart.config.options.nonChartAreaHeight) {
var yAxis = chart.scales['y-axis-0'];
chart.config.options.nonChartAreaHeight = chart.chart.height - (yAxis.bottom - yAxis.top);
}
const barThickness = chart.config.data.datasets[0].barThickness;
const chartAreaHeight = (chart.config.data.labels.length * barThickness * 2);
document.getElementById("chartWrapper").style.height = (chartAreaHeight + chart.config.options.nonChartAreaHeight) + 'px';
}
}],
请注意
aspectRatio
,我们需要定义而不是定义选项maintainAspectRatio: false
。
请查看下面生成两个图表的代码示例。此解决方案使用 Chart.js (2.9.3) 的最新稳定版本。
new Chart('myChart', {
type: 'horizontalBar',
plugins: [{
beforeRender : chart => {
if (!chart.config.options.nonChartAreaHeight) {
var yAxis = chart.scales['y-axis-0'];
chart.config.options.nonChartAreaHeight = chart.chart.height - (yAxis.bottom - yAxis.top);
}
const barThickness = chart.config.data.datasets[0].barThickness;
const chartAreaHeight = (chart.config.data.labels.length * barThickness * 2);
document.getElementById("chartWrapper").style.height = (chartAreaHeight + chart.config.options.nonChartAreaHeight) + 'px';
}
}],
data: {
labels: ['1', '2', '3', '4'],
datasets: [{
barThickness: 20,
data: [100, 90, 80, 70]
}]
},
options: {
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
div {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div id="chartWrapper">
<canvas id="myChart"></canvas>
</div>
推荐阅读
- javascript - 如何使用 Datatables 控制台记录每个选定的行复选框?
- python - numpy.unique vs collections.Counter 性能问题
- java - VS 2017 无法打开包含文件'jni.h'
- google-maps - 无法读取 null - 离子原生谷歌地图的属性“环境”
- docker-compose - TestContainers:重用来自 DockerComposeContainer 的网络以在其他 GenericContainer 中使用?
- wordpress - WordPress Loop Post Types as List und inset sub-posts in
- ->
- ->
- typescript - TypeScript createProgram 抛出 'ts.sys 未定义'
- angular - 如何在角度 4 中使用管道获得 HH:MM
- linux - psplash 图像不出现 (yocto & qemu)
- javascript - 控制台戳中的毫秒似乎在 node.js 中不起作用