首页 > 解决方案 > 如何增加水平条形图js中每个数据集的顶部和底部填充

问题描述

大家好

categoryPercentage据我所知,有一个选项可以使用&增加水平条形图中的顶部和底部填充barPercentage每个数据集但是这个选项是减少条形厚度,我的目标是增加顶部和底部填充以在顶部显示长文本数据标签该栏使用ticks: { mirror: true }选项

在此处输入图像描述

const labels = [
  ['SampleText TextVery', 'LongDescriptionText', 'TextLong WihtLongTextVery'],
  ['SampleText ', 'LongDescription Available', 'TextLong'],
  ['SampleText and', 'LongDescription Texts', 'Text and LongText'],
  ['LongDescription SampleText TextsL'],
  ['SampleText TextsL Texts'],
  ['SampleText TextsL Texts'],
]

const datasets = [
  {
    label: 'Label 1',
    data: [90.1, 90.05, 53.48, 67.16, 49.58, 67.62],
    // categoryPercentage: 1.0,
    // barPercentage: 0.1,
    backgroundColor: '#374774',
  },
  {
    label: 'Label 2',
    data: [81.53, 85.77, 46.53, 67.73, 46.69, 44.45],
    // categoryPercentage: 1.0,
    // barPercentage: 0.1,
    backgroundColor: '#A2B7F3',
  },
]

const el = document.getElementById('myChart')

const ctx = el.getContext('2d')
el.height = labels.length * 256

const options = {
  indexAxis: 'y',
  plugins: {
    legend: { display: false },
  },
  scales: {
    x: {
      grid: { lineWidth: 0 },
      ticks: {
        font: { size: 14 },
        color: '#374774',
      },
      max: 100,
    },
    y: {
      grid: { color: '#DFDFDF' },
      ticks: {
        font: { size: 14 },
        color: '#374774',
        z: 1,
        padding: 0,
        mirror: true,
      },
      max: 100,
    },
  },
}

new Chart(ctx, {
  type: 'bar',
  data: { labels: labels, datasets: datasets },
  options,
})
<div>
  <canvas id="myChart"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

标签: javascriptchart.js

解决方案


推荐阅读