【问题标题】:How to retain spacing between bars for two different bar charts in Chart.js 2如何在 Chart.js 2 中为两个不同的条形图保留条形之间的间距
【发布时间】:2017-08-04 22:10:01
【问题描述】:

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

我的选项对象如下所示,我很难过:

      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,
            },
          }],
        },

【问题讨论】:

    标签: javascript charts chart.js chart.js2


    【解决方案1】:

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

    Chart.js 需要一个围绕画布的容器以允许动态调整大小,因此您还需要将其添加到 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

    【讨论】:

    • 这是缺失的部分。谢谢你。我会在允许的情况下尽快奖励赏金。
    猜你喜欢
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多