react-native-svg-charts

repository·dev·Indexed 25 days ago

https://github.com/jesperlekland/react-native-svg-charts

A library providing customizable SVG-based charts for React Native on iOS, Android, and web. It leverages react-native-svg for rendering and d3 for mathematical calculations and path generation. Supported chart types include Line, Bar, Area, Pie, Circle, and Progress, featuring a decorator system for extensible styling and custom overlays.

Tokens
12.5K
Snippets
15
Records
49
Agent score
81%

What's inside react-native-svg-charts

  1. How to use children as decorators in charts

    dev

    Starting from version 5.0, chart components (and axes) accept React children to act as decorators. This replaces the old extras and decorators props.

    Rules for using children:

    1. Component Type: All children must be a react-native-svg component to be rendered.
    2. Ordering: The order in which you declare children determines the rendering order (z-index).
    3. Positioning: By default, children are rendered on top of the chart. To render a child below the chart, add the prop belowChart={true} to the child component.

    This pattern allows you to declare exactly how and where decorators should appear relative to the chart data.

  2. How decorators work in react-native-svg-charts

    dev

    The library uses a "decorator" system to allow you to style or enhance charts. A decorator is a react-native-svg compliant component passed as a child to a chart component.

    When a component is passed as a child, the chart calls it with specific layout information, allowing the decorator to position itself correctly on the canvas. This makes the library highly extensible, enabling you to add custom elements like labels, points, or overlays to any chart.

  3. Arguments available to chart children

    dev

    When you pass children to a chart component (like <Grid /> or custom decorators), the chart calls them with the following arguments:

    • x: A function that accepts a data point index and returns its 'x' location on the canvas.
    • y: A function that accepts a data point value and returns its 'y' location on the canvas.
    • width: The width of the canvas in pixels.
    • height: The height of the canvas in pixels.
    • ticks: If numberOfTicks was provided to the chart, this array includes the calculated tick values (useful for grids).

    Note for StackedBarChart: This specific chart does not pass the data argument to its children because the original data is not directly useful for layout decorators in a stacked context. Other charts like PieChart do support the data argument and slices array.

  4. Install react-native-svg-charts

    dev

    To use react-native-svg-charts, you must first install react-native-svg and link it to your project, as it is a required dependency for rendering graphs.

    After setting up react-native-svg, install the library using one of the following commands:

    yarn add react-native-svg-charts
    # or
    npm install --save react-native-svg-charts
  5. Layer children in ChartGrouped using the belowChart prop

    dev

    When using ChartGrouped, you can pass children (such as Grids, Axes, or Labels) to control their rendering order relative to the chart paths. The component uses a belowChart prop on children to determine layering:

    1. Below the Chart: Children with belowChart={true} are rendered first (at the bottom of the SVG stack).
    2. The Chart Paths: The main data paths are rendered next.
    3. Above the Chart: Children without the belowChart prop (or where belowChart is false) are rendered last (on top of the paths).

    All children are automatically injected with extraProps, which includes the scales (x, y), data, ticks, width, and height.

  6. Add custom children to PieChart

    dev

    The PieChart accepts children which can be used to overlay or underlay elements (like labels or legends) on the chart.

    Children receive an extraProps object containing:

    • width: The calculated width of the chart.
    • height: The calculated height of the chart.
    • data: The original data array.
    • slices: The processed slices including pieCentroid and labelCentroid.

    Layering with belowChart

    • If a child has the prop belowChart={true}, it is rendered behind the pie slices.
    • If a child does not have belowChart, it is rendered on top of the pie slices.
  7. Extend BarChart with children (Axes and Grids)

    dev

    You can pass children to BarChart to render additional elements like axes or grids. The BarChart component clones these children and injects an extraProps object.

    To ensure elements are rendered in the correct order, use the belowChart prop:

    • Children with belowChart={true}: Rendered behind the bars.
    • Children without belowChart: Rendered on top of the bars.

    Available extraProps injected into children:

    • x: The x-scale function.
    • y: The y-scale function.
    • width: The chart width.
    • height: The chart height.
    • bandwidth: The width (or height if horizontal) of a single bar.
    • ticks: The generated tick values.
    • data: The original data array.
  8. Extend the Chart class to create custom charts

    dev

    The Chart component is a base class intended to be extended. To create a custom chart, you must subclass Chart and override the createPaths method. The createPaths method is responsible for generating the SVG path data used to render the chart elements.

    When you override createPaths, it will receive an object containing:

    • data: The mapped data points (containing x and y values).
    • x: The calculated x-scale function.
    • y: The calculated y-scale function.
  9. Use the `belowChart` prop to layer components

    dev

    The Chart component renders its children in two passes. This allows you to layer components behind or in front of the main chart path.

    1. Background Layers: Any child component with the prop belowChart={true} will be rendered behind the main chart path.
    2. Foreground Layers: Any child component without the belowChart prop will be rendered in front of the main chart path.

    All children receive the following extraProps via React.cloneElement:

    • x, y: The calculated scales.
    • data: The original data array.
    • ticks: The generated y-axis ticks.
    • width, height: The dimensions of the chart.
    • Any additional properties returned by the internal createPaths method (e.g., path).
  10. Configure GroupedBarChart data and SVG styling

    dev

    When using GroupedBarChart, you can control the visual properties of bars using the svg property within your data objects. Styling follows a hierarchical pattern:

    1. Group Level: An svg object inside a group object applies to all bars in that group.
    2. Item Level: An svg object inside an individual data item merges with the group-level svg object, allowing for specific overrides.

    Data Schema

    [
      {
        data: [
          { value: 10, svg: { fill: 'green' } }, // Item level override
          20,                                   // Simple number
          { value: 30, svg: { opacity: 0.5 } } // Object with value
        ],
        svg: { fill: 'blue' }                    // Group level style
      }
    ]
  11. Use PieChart

    dev

    The PieChart component renders a pie or donut chart. Unlike other charts, it requires data to be an array of complex objects (not just numbers). Each object should contain a value and can optionally include an svg object for custom styling or an arc property to override specific arc settings.

    import React from 'react'
    import { PieChart } from 'react-native-svg-charts'
    
    class PieChartExample extends React.PureComponent {
        render() {
            const data = [50, 10, 40, 95, -4, -24, 85, 91, 35, 53, -53, 24, 50, -20, -80]
    
            const randomColor = () => ('#' + ((Math.random() * 0xffffff) << 0).toString(16) + '000000').slice(0, 7)
    
            const pieData = data
                .filter((value) => value > 0)
                .map((value, index) => ({
                    value,
                    svg: {
                        fill: randomColor(),
                        onPress: () => console.log('press', index),
                    },
                    key: `pie-${index}`,
                }))
    
            return <PieChart style={{ height: 200 }} data={pieData} />
        }
    }