簡體   English   中英

如何在 React 中創建帶有 Chart.js 的堆疊水平條形圖?

[英]How do I create a stacked horizontal bar chart with Chart.js in React?

我真的很難找到這個問題的明確答案——尤其是在 React 中。 我想為我的 React 應用程序創建一個堆疊的水平條形圖組件。 這是我要創建的圖表類型: https://codepen.io/pen 下面粘貼的代碼是我到目前為止嘗試使用的代碼,但目前未呈現。

import React, { Component } from 'react';
import Chart from 'chart.js/auto';

export default class LineChart extends Component {
  chartRef = React.createRef();

  componentDidMount() {
    const ctx = this.chartRef.current.getContext('2d');

    new Chart(ctx, {
      type: 'bar',
      data: {
        labels: [
          'Sunday',
          'Monday',
          'Tuesday',
          'Wednesday',
          'Thursday',
          'Friday',
          'Saturday',
        ],
      },
      options: {
        scales: {
          yAxes: [
            {
              stacked: true,
            },
          ],
        },
      },

      datasets: [
        {
          data: [86, 114, 106, 106, 107, 111, 133],
          label: 'Total',
          borderColor: '#3e95cd',
          backgroundColor: '#7bb6dd',
          // fill: False,
        },
        {
          data: [70, 90, 44, 60, 83, 90, 100],
          label: 'Accepted',
          borderColor: '#3cba9f',
          backgroundColor: '#71d1bd',
          // fill: False,
        },
        {
          data: [10, 21, 60, 44, 17, 21, 17],
          label: 'Pending',
          borderColor: '#ffa500',
          backgroundColor: '#ffc04d',
          // fill: False,
        },
        {
          data: [6, 3, 2, 2, 7, 0, 16],
          label: 'Rejected',
          borderColor: '#c45850',
          backgroundColor: '#d78f89',
          // fill: False,
        },
      ],
    });
  }
  render() {
    return (
      <div>
        <canvas id="myChart" ref={this.chartRef} />
      </div>
    );
  }
}

您在使用 V3 時使用 Chart.js 的 V2 語法。 V3 有重大的突破性變化,包括所有規模都是他們自己的 object。對於所有變化,請閱讀遷移指南

當使用對象作為尺度時,你會得到你想要的:

 const options = { type: 'bar', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: 'orange' }, { label: '# of Points', data: [7, 11, 5, 8, 3, 7], backgroundColor: 'pink' } ] }, options: { scales: { y: { stacked: true }, x: { stacked: true } } } } 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.7.1/chart.js"></script> </body>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM