3

I'm trying to create a static (non-clickable) Pie chart using react-chartjs-2.
However I want one of the slices to "pop out", or appear bigger than the others:

Visual example of the pie chart I'm trying to create

Hence, I'm trying to access one of the slices in the pie chart and modify its outerRadius property.


I've encountered multiple similar questions both in Stack Overflow and in Github, which helped me come up with this:

import { Pie } from 'react-chartjs-2';

<Pie
    data={data}
    options={options}
    getElementsAtEvent={(elems) => {
        // Modify the size of the clicked slice
        elems[0]['_model'].outerRadius = 100;
    }}
/>

However I didn't find anything about getting a slice to pop out without the user clicking it.

GalAbra
  • 5,048
  • 4
  • 23
  • 42

2 Answers2

1

After looking under Pie component's hood, I ended up finding the answer.
You can find it inside componentDidMount():

import React, { Component } from 'react';
import { Pie } from 'react-chartjs-2';

class PieChart extends Component {
    componentDidMount() {
        const change = {
            sliceIndex: 0,
            newOuterRadius: 100
        }
        const meta = this.pie.props.data.datasets[0]._meta;
        meta[Object.keys(meta)[0]]
            .data[change.sliceIndex]
            ._model
            .outerRadius = change.newOuterRadius;
    }

    render() {
        const data = {
            type: 'pie',
            datasets: [ { data: [10, 20, 30] } ],
            labels: ['a', 'b', 'c'],
        };
        const options = {};

        return <Pie
            ref={(self) => this.pie = self}
            data={data}
            options={options}
        />
    }
}

export default PieChart;
GalAbra
  • 5,048
  • 4
  • 23
  • 42
1

I have one more solution with version 4.3.1. Try to add offset property into datasets.

import { Pie } from 'react-chartjs-2';

<Pie
    data={
      datasets: [
        {
          data: [1, 1],
          borderColor: ['black', 'transparent'],
          offset: [10, 0],
        },
      ],
    }
/>

It will render Pie with 2 segments. For the first segment, you will have black border and 10px offset