# Pie chart

## Component Visuals

{% tabs %}
{% tab title="Overview" %}

<figure><img src="https://1173113760-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYEKIeE9xnHLXuuwEs8zo%2Fuploads%2FPu4Ickpo0MakShzuVZqP%2FPie%20chart.png?alt=media&#x26;token=8936dc68-93df-49d1-94e1-59b96d336baf" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="Visual 1" %}

<figure><img src="https://1173113760-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYEKIeE9xnHLXuuwEs8zo%2Fuploads%2FG9IzsPjt0M4uPl9G0m8m%2FPie%20chart%20v1.png?alt=media&#x26;token=5a4c9f01-0a7b-40bf-abb3-17effe0cae59" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="Visual 2" %}

<figure><img src="https://1173113760-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYEKIeE9xnHLXuuwEs8zo%2Fuploads%2F1eq4WyYPoEhcYvZPvzkv%2FPie%20chart%20v2.png?alt=media&#x26;token=685506f9-dcdf-47a0-a590-e2fa363614f4" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="Visual 3" %}

<figure><img src="https://1173113760-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYEKIeE9xnHLXuuwEs8zo%2Fuploads%2FEN2tlIofSq4LP8CqnIJN%2FPie%20chart%20v3.png?alt=media&#x26;token=5fa00419-a72d-4500-8b48-65062da7d6b7" alt=""><figcaption></figcaption></figure>
{% endtab %}
{% endtabs %}

### Installation

To use the `Chart` component, you need to install the Quest Labs React SDK:

* Open your terminal/command prompt.
* Navigate to your project's root directory using the `cd` command if you're not already there.
* Run the following command to install the `quest-sdk` package using npm:

```bash
npm install @questlabs/react-graphs
```

> This command will download and install the package and its dependencies into your project.

*Note: The Quest Labs React Graph SDK includes ECharts as a dependency. When you install `@questlabs/react-graphs`, ECharts will be automatically installed as well. ECharts is a powerful charting library used by the Quest Labs SDK to render various types of charts, including the* `Chart.Pie` *component.*

{% hint style="info" %}
Make sure your project has npm and Node.js installed, and that you have the necessary permissions to install packages in your project directory.
{% endhint %}

### Features

The `Chart.Pie` component from Quest Labs SDK offers powerful features for creating interactive and visually appealing line charts in your React applications:

* **Theme Support:** Customize the appearance of the line chart using themes. Themes allow you to define colors, fonts, and other visual properties to match your application's design system.
* **Data-driven:** Visualize data easily with the `Chart.Pie` component by providing an array of data points. Each data point consists of x and y coordinates, enabling you to display trends and patterns over time or other variables.
* **Tooltip Integration:** Easily add tooltips to display additional information when users hover over data points. Tooltips enhance interactivity and provide contextual details about data values.
* **Event Callbacks:** Utilize event callbacks such as `onChartLoad`, `onChartLoaded`, and `onChartInitialized` to handle chart loading states, data retrieval, and initialization. These callbacks help manage chart lifecycle events efficiently.
* **React Integration:** Built with React in mind, the `Chart.Pie` component integrates smoothly into React applications. It leverages React's state management and component lifecycle methods for efficient data handling and rendering.

### Props

`Chart` component props

| Prop Name              | Type                          | Required | Details                                                                                          |
| ---------------------- | ----------------------------- | -------- | ------------------------------------------------------------------------------------------------ |
| **children**           | JSX.Element \| JSX.Element\[] | No       | The children components to be rendered inside the chart container.                               |
| **chartId**            | string                        | No       | The unique identifier for the chart. Generated through QuestApp.                                 |
| **theme**              | object                        | No       | The theme configuration for the chart.                                                           |
| **data**               | PieChartDataset\[]            | No       | The dataset for the chart. Each data object should follow the `ChartDataset` type structure.     |
| **setData**            | function                      | No       | The function to set the dataset. It can accept `SetStateAction` for various chart datasets.      |
| **onChartInitialized** | function                      | No       | Callback function invoked when the chart is initialized.                                         |
| **onChartLoaded**      | function                      | No       | Callback function invoked when the chart data is loaded. Optional parameter for the loaded data. |
| **onChartLoad**        | function                      | No       | Callback function invoked when the chart starts loading.                                         |
| **height**             | string \| number              | No       | The height of the chart container.                                                               |
| **width**              | string \| number              | No       | The width of the chart container.                                                                |

`Chart.Pie` component props\ <br>

| Prop Name     | Type             | Required | Details                                                                                       |
| ------------- | ---------------- | -------- | --------------------------------------------------------------------------------------------- |
| **legend**    | object           | No       | The configuration for the chart legend, including position, formatter, icon, and text styles. |
| **grid**      | object           | No       | The configuration for the chart grid, including position and label containment.               |
| **xAxis**     | Axis             | No       | The configuration for the x-axis, including type, visibility, formatter, and styles.          |
| **yAxis**     | Axis             | No       | The configuration for the y-axis, including type, visibility, formatter, and styles.          |
| **toolbox**   | object           | No       | The configuration for the toolbox component.                                                  |
| **tooltip**   | object           | No       | The configuration for the tooltip, including styles and alignment options.                    |
| **zoom**      | object           | No       | The configuration for zooming, including enabling wheel/slider zoom, start/end, and styles.   |
| **resizable** | boolean          | No       | Whether the chart is resizable.                                                               |
| **height**    | string \| number | No       | The height of the line chart container.                                                       |
| **width**     | string \| number | No       | The width of the line chart container.                                                        |

### Types

```typescript
type PieChartDatasetLabelLine = LineStyle & {
    length?: number;
    length2?: number;
    lineStyle?: LineStyle;
    show?: boolean;
    smooth?: boolean;
}
type PieChartDatasetLabel = ItemStyle<Style> & TextBorderStyle & TextShadowStyle & {
    align?: Align;
    show?: boolean;
}

type PieChartDatasetEmphasis = {
    scale?: boolean;
    scaleSize?: number;
    focus?: 'none' | 'self' | 'series';
    labelLine?: PieChartDatasetLabelLine;
    label?: PieChartDatasetLabel;
    pieStyle?: ItemStyle<StyleWithGradient>
}

type PieChartDataset = {
    id?: string;
    data: number[] | number[][];
    name?: string;
    cursor?: 'auto' | 'default' | 'pointer' | 'move' | 'text' | 'wait' | 'help' | 'not-allowed' | 'crosshair' | 'grab'| 'grabbing' | 'zoom-in' | 'zoom-out';
    extraData?: any;
    show?: boolean
    showLabel?: boolean;
    radius?: [string | number, string | number] | string | number;
    label?: PieChartDatasetLabel,
    labelLine?: PieChartDatasetLabelLine,
    pieStyle?: ItemStyle<StyleWithGradient>;
    emphasis?: PieChartDatasetEmphasis,
    labelPosition?: "center" | "inner" | "outer" | "outside";
    startAngle?: number;
    data: (StyleWithGradient & BorderStyle & ShadowStyle & {
        value: number; 
        name: string;
        borderRadius?: number;
        emphasis?: PieChartDatasetEmphasis
    })[];
    animationDelay?: number;
    animationDuration?: number;
    animationEasing?: "backIn" | "backInOut" | "backOut" | "bounceIn" | "bounceInOut" | "bounceOut" | "circularIn" | "circularInOut" | "circularOut" | "cubicIn" | "cubicInOut" | "cubicOut" | "quinticIn" | "quinticInOut" | "quinticOut" | "sinusoidalIn" | "sinusoidalInOut" | "sinusoidalOut" | "elasticInOut" | "elasticout" | "exponentialIn" | "exponentialInOut" | "exponentialOut" | "linear" | "quadraticIn" | "quadraticInOut" | "quadraticout" | "quarticIn" | "quarticInOut" | "quarticout";
}

type Axis = {
    type?: 'time' | 'category' | 'log' | 'value';
    show?: boolean;
    formatter?: string | ((param: string) => string);
    showSplitLine?: boolean;
    showAxisLine?: boolean;
    splitLineStyle?: LineStyle;
    axisLineStyle?: LineStyle;
    labelStyle?: FontStyle & TextBorderStyle & TextShadowStyle & {
        fontFamily?: string;
        fontSize?: number | string;
        fontWeight?: 'bold' | 'bolder' | 'lighter' | 'normal';
        fontStyle?: 'italic' | 'normal' | 'oblique';
        textBorderWidth?: number;
        textBorderColor?: string;
        textBorderType?: 'dashed' | 'dotted' | 'solid';
        textBorderDashOffset?: number;
        textShadowBlur?: number;
        textShadowColor?: string;
        textShadowOffsetX?: number;
        textShadowOffsetY?: number;
        margin?: number;
        align?: Align;
        verticalAlign?: 'bottom' | 'middle' | 'top';
        color?: string;
    },
    min?: number;
    max?: number;
    data?: string[] | number[];
    boundaryGap?: string | [string, string]
}
```

### Usage

To integrate the `Chart.Pie` component into your React application, follow these steps

* **Import the CSS**: In your JavaScript or TypeScript file where you're using the `Chart.Pie`, import the CSS styles for the component. This ensures that the component's styling is applied correctly.

```jsx
import '@questlabs/react-graphs/dist/style.css'
```

* **Import the Chart Component**: Import the `Chart`component from the `@questlabs/react-graphs` package.

```jsx
import { Chart } from '@questlabs/react-graphs';
```

## Example Usage

Here's an example of how to use the `Chart.Pie`  component within your React application.

```typescript
import React from 'react'
import { Chart, Gradient } from '@questlabs/react-graphs'
import type { PieChartDataset } from '@questlabs/react-graphs'
import '@questlabs/react-graphs/dist/style.css'

const pieChartData: PieChartDataset[] = [
  {
    name: 'pi',
    data: [
      {
        name: 'Other Sales',
        value: 30,
        color: Gradient({ x: 1, y: 1, r: 3, colorStop: [{ color: 'red', offset: 0 }, { color: 'blue', offset: 1 }] }),
      },
      {
        name: 'Hybrid Sales',
        value: 30,
        color: 'rgba(144, 53, 255, 1)'
      },
      {
        name: 'Offline Sales',
        value: 10,
        color: 'rgba(114, 0, 235, 1)'
      },
      {
        name: 'Online Sales',
        value: 30,
        color: 'rgba(85, 0, 179, 1)'
      }
    ],
    startAngle: 100
  }
]

export default function App() {
  return (
    <div style={{ display: 'grid', height: '100vh', placeItems: 'center', background: 'whitesmoke' }}>
      <Chart data={pieChartData} setData={() => { }} style={{ width: 400 }}>
        <Chart.Header>
          <Chart.Title>
            Pie Chart
          </Chart.Title>
          <Chart.Option onSelect={console.log}>
            <Chart.Item label="Last 90 days" value="LAST_90D" />
            <Chart.Item label="Last 90 days" value="LAST_90D" />
          </Chart.Option>
          <Chart.Info>
            This is my pie chart component
          </Chart.Info>
        </Chart.Header>
        <div style={{ padding: '10px 20px', display: 'flex', gap: 10 }}>
          <Chart.DatePicker value="03-05-2020" label="Start Date" />
          <Chart.DatePicker value="03-05-2024" label="End Date" />
        </div>
        <Chart.Pie />
      </Chart>
    </div>
  )
}
```

You can fully customize the chart layout and use the `useChart<ChartContextSingleType>` hook provided by `@questlabs/react-graphs`. This hook provides various options.<br>

```typescript
type ChartContextSingleType<T extends ChartDataset> = {
    theme?: Record<string, string>;
    data: T[];
    setData: React.Dispatch<SetStateAction<T[]>>;
    loading: boolean;
    getChartId: () => string;
    setChartId: (chartId: string) => void;
    getQuery: () => string;
    setQuery: (queryString: string) => void;
    refetch: (props?: {chartId?: string, query?: string}) => Promise<T>;
    title?: string;
}
```

### Demo

Check a demo video for better understanding.

{% embed url="<https://drive.google.com/file/d/1UwICS0ZiAcOoMNIXgnABbn307YkNjY7a/view?usp=sharing>" %}
