是否可以更改每个数据集的 ChartJS 气泡图元素的 pointStyle?

Str*_*ine 5 chart.js

我有一个包含多个数据集的 ChartJS v2 气泡图,我想用不同形状的元素表示某些数据点。

我已经阅读了有关 pointStyle 的点配置选项的信息,因此元素点可以是除圆形之外的不同形状。

我尝试了一些变体和位置来添加 pointStyle 但我无法让它工作。我只看到圆圈。

这甚至可以通过气泡图实现吗?如果不行的话可以用散点图吗?

Lee*_*lee 1

如果有人还需要知道这一点。您可以将其放在数据集本身中以仅应用于该数据集,放在中options.datasets.bubble以使其应用于所有气泡数据集,放在中options.elements.point以将其应用于所有点元素或放在选项的根中以将其应用于整个图表:

const image = new Image()
image.src = 'https://www.chartjs.org/docs/master/favicon.ico';

const options = {
  type: 'bubble',
  data: {
    datasets: [{
      label: '# of Votes',
      data: [{
          x: 20,
          y: 30,
          r: 15
        }, {
          x: 40,
          y: 10,
          r: 10
        },
        {
          x: 30,
          y: 22,
          r: 25
        }
      ],
      pointStyle: (ctx) => (ctx.dataIndex === 2 ? image : 'rectRot'),
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)'
    }]
  },
  options: {
    pointStyle: (ctx) => (ctx.dataIndex === 2 ? image : 'rectRot'),
    elements: {
      point: {
        pointStyle: (ctx) => (ctx.dataIndex === 2 ? image : 'rectRot')
      }
    },
    datasets: {
      bubble: {
        pointStyle: (ctx) => (ctx.dataIndex === 2 ? image : 'rectRot')
      }
    }
  }
}

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

您可以向 pointStyle 传递画布元素、图像或以下字符串之一:

  • '圆圈'
  • '叉'
  • '交叉腐烂'
  • '短跑'
  • '线'
  • '直'
  • '矩形'
  • '直旋转'
  • '星星'
  • '三角形'