0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

chartjs-plugin-datalabels メモ

Last updated at Posted at 2024-04-18

仕事でグラフ使うよ

チャットGPTにいい感じに書いてもらったよ

これで明日のタスクできるよ

ありがと

import { Bar, Pie } from 'react-chartjs-2';
import { Chart, registerables } from "chart.js"
import ChartDataLabels from 'chartjs-plugin-datalabels';
Chart.register(...registerables)


const data = {
  labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange', 'Black', 'White', 'Gray', 'Brown', 'Pink'],
  datasets: [
    {
      label: '# of Votes',
      data: [12, 19, 5, 5, 2, 3, 8, 7, 4, 3, 6], // 値が0以外の項目を含むデータセット
      backgroundColor: [
        'red',
        'blue',
        'yellow',
        'green',
        'purple',
        'orange',
        'black',
        'white',
        'gray',
        'brown',
        'pink'
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)',
        'rgba(0, 0, 0, 1)',
        'rgba(255, 255, 255, 1)',
        'rgba(128, 128, 128, 1)',
        'rgba(165, 42, 42, 1)',
        'rgba(255, 192, 203, 1)'
      ],
      borderWidth: 1,
    },
  ],
};


const options = {
  plugins: {
    legend: {
      position: 'bottom',
    },
    datalabels: {
      color: '#fff',
      anchor: 'end', // ラベルをグラフの外側に表示
      align: 'start', // ラベルの位置を調整
      offset: 10, // ラベルのオフセットを調整
      clamp: true, // ラベルをグラフの内側に制限
      font: {
        size: 12, // フォントサイズを調整
        weight: 'normal' // フォントウェイトを調整
      },
      formatter: (value, ctx) => {
        return `${ctx.chart.data.labels[ctx.dataIndex]}: ${value}`;
      }
    }
  },
  // グラフのサイズや位置を微調整するためのオプション
  layout: {
    padding: {
      top: 20,
      bottom: 20,
      left: 20,
      right: 20
    }
  }
};


export default function App() {
  return (
    <>
      <div className="w-96">
        <div>
          <h2>Pie Chart Example</h2>
          <Pie data={data} options={options} width={1000} height={300} plugins={[ChartDataLabels]} />
        </div>
      </div>
    </>
  );
}

ちなみにtypescriptだと型エラーが出るよ

そんな時はエラー無視しよう、どうせ型エラーだしいいよね?

{/* @ts-ignore */} 
 <Pie data={data} options={options} width={1000} height={300} 
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?