【问题标题】:ChartJS fails to render horizontal bar chart for timeseries dataChartJS 无法为时间序列数据呈现水平条形图
【发布时间】:2020-02-07 09:12:46
【问题描述】:

这是一个笨蛋 https://embed.plnkr.co/plunk/49kIfy8OShzlzu5J 这解释了问题。

如果图表type 更改为barline,它工作正常。但它无法呈现horizontalBar - 没有错误或警告表明任何问题(如果有)。

horizontalBar 是否需要用户手动明确地设置标签,还是我在这里缺少配置设置?

【问题讨论】:

    标签: javascript chart.js bar-chart timeserieschart


    【解决方案1】:

    使用horizontalBar 时,您必须确保您的yAxis 定义为type: 'time'。您的数据也必须反映这一点并提供正确轴的数据。

    { y: '2020-01-01T00:00:00', x: Math.random() * 20 }
    

    这可能如下所示:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Line Chart</title>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js"></script>
        <style>
          canvas {
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
          }
        </style>
      </head>
    
      <body>
        <div style="height: 450px; width: 300px">
          <canvas id="canvas"></canvas>
        </div>
        <script>
          const config = {
            type: 'horizontalBar',
            options: {
              title: { text: 'Bar Chart', display: true },
              responsive: true,
              maintainAspectRatio: false,
              scales: {
                yAxes: [
                  {
                    offset: true,
                    type: 'time'
                  },
                ]
              },
            },
            data: {
              datasets: [
                {
                  label: 'Label 1',
                  borderColor: '#40407a',
                  backgroundColor: '#d1ccc0',
                  borderWidth: 3,
                  data: [
                    { y: '2020-01-01T00:00:00', x: Math.random() * 20 },
                    { y: '2020-01-01T01:00:00', x: Math.random() * 20 },
                    { y: '2020-01-01T01:20:00', x: Math.random() * 20 },
                    { y: '2020-01-01T02:10:00', x: Math.random() * 20 },
                    { y: '2020-01-01T02:35:00', x: Math.random() * 20 },
                    { y: '2020-01-01T03:00:00', x: Math.random() * 20 },
                  ],
                },
              ],
            },
          };
    
          window.onload = function() {
            var ctx = document.getElementById('canvas').getContext('2d');
            window.myLine = new Chart(ctx, config);
          };
        </script>
      </body>
    </html>

    【讨论】:

    • 文档有点混乱,它说“在条形图中的 x 轴上指定的任何选项,都应用于水平条形图中的 y 轴” - 这意味着库会照顾使用适当的选项。感谢您指出我们可以手动切换 x 轴和 y 轴配置来实现这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2016-08-21
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多