首页 > 解决方案 > Chart JS:可以在 Chart JS 中混合散点图和条形图吗?

问题描述

在此处输入图像描述

我在 matplotlib python 中有这个图,这是一个直方图和一些具体的函数。我正在使用条形/折线混合图表尝试与 ChartJS 相同的情节。问题是两个图的 x 轴点必须相同,并且没有实现函数的形式。这个情节在 Chart JS 中是否可行。如果没有,我可以使用哪些库?

标签: javascriptchartschart.jshistogram

解决方案


是的,这可以通过使用具有相同标签但偏移量和显示设置为 false 的第二个 x 轴来实现:

const labels = ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"];

const options = {
  type: 'bar',
  data: {
    labels,
    datasets: [{
        type: 'line',
        xAxisID: 'x2',
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange',
        backgroundColor: 'orange'
      },
      {
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink',
        backgroundColor: 'pink'
      }
    ]
  },
  options: {
    scales: {
      x: {},
      x2: {
        labels,
        offset: false,
        display: false
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>


推荐阅读