首页 > 解决方案 > 图表 js 2 个条形图,顶部有一个自定义标签

问题描述

我有几个像 A 和 B 这样的值,现在我有一对我在 chart-js 上显示它们,就像这样

在此处输入图像描述

现在对于我的用例,我使用 A 和 BEg a=100 和 b=50 计算第三个值,除以它们将得到 c=2.0。现在我想在 A 和 B 栏上显示这个 c 值作为一个像这样的公共标签

在此处输入图像描述

"chart.js": "^3.3.0", react-js

const newChartInstance = new Chart(chartContainer.current, {
  

  type: "bar",
    options: {
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
            },
          },
        ],
      },
      ...config.options,

      onClick: (e) => {
        const points = newChartInstance.getElementsAtEventForMode(
          e,
          "nearest",
          { intersect: true },
          true
        );

        if (points.length) {
          const firstPoint = points[0];

          var type =
            newChartInstance.data.datasets[firstPoint.datasetIndex].label;
          var label = newChartInstance.data.labels[firstPoint.index];
          var value =
            newChartInstance.data.datasets[firstPoint.datasetIndex].data[
              firstPoint.index
            ];
          // This is the result that you will use to breakdown the chart
          //console.log(label, value, type);
          dispatch(setClickedBar({ label, value, type, tile: props.tile }));
        }
      },
    },
    data: data,
  });

标签: javascriptreactjschart.js

解决方案


您可以为此使用自定义插件:

var options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: 'red'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        backgroundColor: 'blue'
      }
    ]
  },
  options: {
    plugins: {
      customValue: {
        name: 'ROI',
      }
    }
  },
  plugins: [{
    id: 'customValue',
    afterDraw: (chart, args, opts) => {
      const {
        ctx,
        data: {
          datasets
        },
        _metasets
      } = chart;

      datasets[0].data.forEach((dp, i) => {
        let barValue = `${(datasets[1].data[i] + dp) / 2}%`;
        const lineHeight = ctx.measureText('M').width;
        const textVal = opts.name || 'fill'

        ctx.textAlign = 'center';

        ctx.fillText(barValue, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 1.5), _metasets[0].data[i].width);
        ctx.fillText(textVal, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 3), _metasets[0].data[i].width);
      });
    }
  }]
}

var 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.4.1/chart.js"></script>
</body>


推荐阅读