1

使用 react-chartjs-2,创建条形图如下。我正在尝试将图例制作成方形而不是默认矩形。

我应用了 boxWidth: 10 如下但它不起作用,是否有任何其他可能的替代方法来生成方形图例

const sample_data = {
  labels: ['Item1', 'Item2'],
  datasets: [
    {
      data: [10, 10, 50],
      borderWidth: 1,
      backgroundColor: 'yellow',
    },
    { data: [20, 20, 20], 
      borderWidth: 1,
      backgroundColor: 'green' 
    },
  ],
};
const sample_options = {
  responsive: true,
  legend: {
    boxWidth: 10, // Also 0 doesn't make any change
  },
...
};
<Bar data={sample_data} options={sample_options} />;
4

1 回答 1

2

您必须将 boxWidth 放在图例选项的标签部分中,如文档中所述:https ://www.chartjs.org/docs/latest/configuration/legend.html#legend-label-configuration

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    legend: {
      labels: {
        boxWidth: 10
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

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/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>

于 2021-02-11T18:54:46.497 回答