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

标签 chart.js

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

我已经阅读了 pointStyle 的点配置选项,因此元素点可以是不同的形状,而不是圆形。

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

这甚至可以用气泡图实现吗? 如果不能,是否可以使用散点图?

最佳答案

如果有人还需要知道这个。您可以将它放在数据集本身中以仅应用于该数据集,在 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);
<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>

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

  • “圈子”
  • '交叉'
  • 'crossRot'
  • '破折号'
  • '线'
  • '正交'
  • 'rectRounded'
  • 'rectRot'
  • '明星'
  • '三角形'

关于chart.js - 是否可以更改每个数据集的 ChartJS 气泡图元素的 pointStyle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42005295/

相关文章:

reactjs - Chart.js - 增加 y 轴和第一个栏之间的空间

javascript - 将 ng2-charts 与加载程序和 AfterViewInit 一起使用

javascript - 无法使用 Chart.js 制作图表

javascript - chart.js 删除悬停效果

chart.js - 如何在线图上添加填充?

chart.js - 如何更新 chartjs2 选项(scale.tick.max)

javascript - Chart.js 仅显示最后一个数据值

javascript - 通过 ChartJS 的交互式图表

tooltip - ng2-chart.js 工具提示始终显示

javascript - 如何在javascript中推送多维数组