Giter Club home page Giter Club logo

react-native-svg-charts's Introduction

react-native-svg-charts

version downloads license

Welcome to react-native-svg-charts!

react-native-svg-charts provides SVG Charts support to React Native on iOS and Android, and a compatibility layer for the web.

Looking for maintainers! I alone don't have the time to maintain this library anymore. Preferably looking for somebody who uses this library in their proffesional work (how I originally got the time to maintain).

version 5 is now available!

A much improved decorator system has been introduced, allowing for greater flexibility and less complexity. See releases for more information.


In order to not bloat this README too much we've moved some examples over to react-native-svg-charts-examples. There we will try to showcase the really cool things you can do with this library. This README will try to keep things as simple as possible so that everybody can get up and running as fast as possible.

Prerequisites

This library uses react-native-svg to render its graphs. Therefore this library needs to be installed AND linked into your project to work.

Other than the above dependency this library uses pure javascript and supports both iOS and Android

Getting Started

Make sure to follow the installation mentioned in the Prerequisites

Then you can install the library using either yarn:

yarn add react-native-svg-charts

or npm:

npm install --save react-native-svg-charts

Now you're good to go!

Motivation

Creating beautiful graphs in React Native shouldn't be hard or require a ton of knowledge. We use react-native-svg in order to render our SVG's and to provide you with great extensibility. We utilize the very popular d3 library to create our SVG paths and to calculate the coordinates.

We built this library to be as extensible as possible while still providing you with the most common charts and data visualization tools out of the box. We're very proud of our "decorator" support. All charts can be extended with "decorators", a component that somehow styles or enhances your chart. Simply pass in a react-native-svg compliant component as a child to the graph and it will be called with all the necessary information to layout your decorator. See each chart for information on what data the decorator will be called with.

Feedback and PR's are more than welcome ๐Ÿ™‚

Running

If you want to test out the library you can clone this repository and run it. We suggest that you test out the storybooks that we've implemented. Most of the charts are implemented with knobs so that you can tweak most properties and see their behavior live.

Clone the repo and run the following:

yarn

# for iOS
(cd ios && pod install)
react-native run-ios

# for Android
react-native run-android

yarn storybook

# and then reload your device

Common Props

Property Default Description
data required An array of arbitrary data - use prop xAccessor/yAccessorto tell the chart about the data structure
yAccessor ({ item }) => item A function that takes each entry of data (named "item") as well as the index and returns the y-value of that entry
xAccessor ({ index }) => index Same as yAccessor but returns the x-value of that entry
yScale d3Scale.scaleLinear A function that determines the scale of said axis (only tested with scaleLinear, scaleTime & scaleBand )
xScale d3Scale.scaleLinear Same as yScale but for the x axis
svg {} an object containing all the props that should be passed down to the underlying react-native-svg component. See available props
animate false PropTypes.bool
animationDuration 300 PropTypes.number
style undefined Supports all ViewStyleProps
curve d3.curveLinear A function like this
contentInset { top: 0, left: 0, right: 0, bottom: 0 } An object that specifies how much fake "margin" to use inside of the SVG canvas. This is particularly helpful on Android where overflow: "visible" isn't supported and might cause clipping. Note: important to have same contentInset on axis's and chart
numberOfTicks 10 We use d3-array to evenly distribute the grid and dataPoints on the yAxis. This prop specifies how many "ticks" we should try to render. Note: important that this prop is the same on both the chart and on the yAxis
showGrid true Whether or not to show the grid lines
yMin undefined Alter how the chart bounds are calculated
yMax undefined Alter how the chart bounds are calculated
xMin undefined Alter how the chart bounds are calculated
xMax undefined Alter how the chart bounds are calculated
children undefined One or many react-native-svg components that will be used to enhance your chart

Common arguments to children

Property Description
x a function that normally accepts the index of a data point an returns its 'x' location on the canvas
y a function that normally accepts the value of a data point an returns its 'y' location on the canvas
width the width of the canvas in pixels
height the height of the canvas in pixels
data the same data array provided to the chart, use this to map over your data points if you want decorators on each point
ticks if numberOfTicks has been provided to the chart this array will include the calculated tick values (useful for grids)

Components

This library currently provides the following components

Also see

AreaChart

Area chart

Example

import React from 'react'
import { AreaChart, Grid } from 'react-native-svg-charts'
import * as shape from 'd3-shape'

class AreaChartExample extends React.PureComponent {
    render() {
        const data = [50, 10, 40, 95, -4, -24, 85, 91, 35, 53, -53, 24, 50, -20, -80]

        return (
            <AreaChart
                style={{ height: 200 }}
                data={data}
                contentInset={{ top: 30, bottom: 30 }}
                curve={shape.curveNatural}
                svg={{ fill: 'rgba(134, 65, 244, 0.8)' }}
            >
                <Grid />
            </AreaChart>
        )
    }
}

Props

See Common Props

Property Default Description
start 0 The value of which the area should start (will always end on the data point)

Arguments to children

Supports all Common arguments to children

StackedAreaChart

Very similar to an area chart but with multiple sets of data stacked together. We suggest that you read up on d3 stacks in order to better understand this chart and its props See Area stack chart with Y axis to see how to use a YAxis with this component Use the svgs prop to pass in react-native-svg compliant props to each area.

Stacked area chart

Example

import React from 'react'
import { StackedAreaChart } from 'react-native-svg-charts'
import * as shape from 'd3-shape'

class StackedAreaExample extends React.PureComponent {
    render() {
        const data = [
            {
                month: new Date(2015, 0, 1),
                apples: 3840,
                bananas: 1920,
                cherries: 960,
                dates: 400,
            },
            {
                month: new Date(2015, 1, 1),
                apples: 1600,
                bananas: 1440,
                cherries: 960,
                dates: 400,
            },
            {
                month: new Date(2015, 2, 1),
                apples: 640,
                bananas: 960,
                cherries: 3640,
                dates: 400,
            },
            {
                month: new Date(2015, 3, 1),
                apples: 3320,
                bananas: 480,
                cherries: 640,
                dates: 400,
            },
        ]

        const colors = ['#8800cc', '#aa00ff', '#cc66ff', '#eeccff']
        const keys = ['apples', 'bananas', 'cherries', 'dates']
        const svgs = [
            { onPress: () => console.log('apples') },
            { onPress: () => console.log('bananas') },
            { onPress: () => console.log('cherries') },
            { onPress: () => console.log('dates') },
        ]

        return (
            <StackedAreaChart
                style={{ height: 200, paddingVertical: 16 }}
                data={data}
                keys={keys}
                colors={colors}
                curve={shape.curveNatural}
                showGrid={false}
                svgs={svgs}
            />
        )
    }
}

Props

Property Default Description
data required An array of the data entries
keys required This array should contain the object keys of interest (see above example)
colors required An array of equal size as keys with the color for each key
order d3.stackOrderNone The order in which to sort the areas
offset d3.stackOffsetNone A function to determine the offset of the areas

Also see Common Props

Arguments to children

Property Description
x a function that normally accepts the index of a data points an returns its 'x' location on the canvas
y a function that normally accepts the value of a data points an returns its 'y' location on the canvas
width the width of the canvas in pixels
height the height of the canvas in pixels
data ~~the same data array provided to the chart, use this to map over your data points if you want decorators on each point~
ticks if numberOfTicks has been provided to the chart this array will include the calculated tick values (useful for grids)

This chart does not call a child with the data argument. This is due to the fact that a lot of calculations go into creating the stacked chart, meaning that the original data prop doesn't provide especially valuable information when trying to layout decorators. It does however call with the rest of the common arguments

BarChart

Bar chart

Example

import React from 'react'
import { BarChart, Grid } from 'react-native-svg-charts'

class BarChartExample extends React.PureComponent {
    render() {
        const fill = 'rgb(134, 65, 244)'
        const data = [50, 10, 40, 95, -4, -24, null, 85, undefined, 0, 35, 53, -53, 24, 50, -20, -80]

        return (
            <BarChart style={{ height: 200 }} data={data} svg={{ fill }} contentInset={{ top: 30, bottom: 30 }}>
                <Grid />
            </BarChart>
        )
    }
}

Props

Also see Common Props

Property Default Description
data required The data prop in a barChart can look exactly like in a Line- or AreaChart, i.e an array of just numbers or complex objects. It can however also be an array with several data sets. A data object can contain a svg property which allows you two override styles on that specific object. See the examples repo
horizontal false Boolean whether or not the bars should be horizontal
svg {} Default svg props for all bars. Supports all svg props an svg path normally supports. This styles will be overriden if there are specific styles for a given data object
spacingInner 0.05 Spacing between the bars (or groups of bars)
spacingOuter 0.05 Spacing outside of the bars (or groups of bars). Percentage of one bars width
contentInset { top: 0, left: 0, right: 0, bottom: 0 } PropTypes.shape

Arguments to children

Property Description
bandwidth the width of a band (a.k.a bar)

Also supports all Common arguments to children

StackedBarChart

The same as the StackedAreaChart except with bars (and different svgs prop). We suggest that you read up on d3 stacks in order to better understand this chart and its props

The svgs prop here is not based on keys, but rather entries, as the user might want to specify different props for each entry in each bar. Therefore each key entry can contain a complex object that contains e.g an svg prop. See this example for inspiration

Stacked bar chart Stacked bar chart - horizontal

Example

import React from 'react'
import { StackedBarChart } from 'react-native-svg-charts'

class StackedBarChartExample extends React.PureComponent {
    render() {
        const data = [
            {
                month: new Date(2015, 0, 1),
                apples: 3840,
                bananas: 1920,
                cherries: 960,
                dates: 400,
                oranges: 400,
            },
            {
                month: new Date(2015, 1, 1),
                apples: 1600,
                bananas: 1440,
                cherries: 960,
                dates: 400,
            },
            {
                month: new Date(2015, 2, 1),
                apples: 640,
                bananas: 960,
                cherries: 3640,
                dates: 400,
            },
            {
                month: new Date(2015, 3, 1),
                apples: 3320,
                bananas: 480,
                cherries: 640,
                dates: 400,
            },
        ]

        const colors = ['#7b4173', '#a55194', '#ce6dbd', '#de9ed6']
        const keys = ['apples', 'bananas', 'cherries', 'dates']

        return (
            <StackedBarChart
                style={{ height: 200 }}
                keys={keys}
                colors={colors}
                data={data}
                showGrid={false}
                contentInset={{ top: 30, bottom: 30 }}
            />
        )
    }
}

Props

Property Default Description
data required An array of the data entries: each value can be a number or a complex object with custom svg props for example
keys required This array should contain the object keys of interest (see above example)
colors required An array of equal size as keys with the color for each key
valueAccessor ({ item, key }) => item[key] Very similar to the yAccessor of the other charts, usually needed when using complex objects as values
horizontal false Boolean whether or not the bars should be horizontal
order d3.stackOrderNone The order in which to sort the areas
offset d3.stackOffsetNone A function to determine the offset of the areas

Also see Common Props

Arguments to children

Property Description
x a function that normally accepts the index of a data points an returns its 'x' location on the canvas
y a function that normally accepts the value of a data points an returns its 'y' location on the canvas
width the width of the canvas in pixels
height the height of the canvas in pixels
data the same data array provided to the chart, use this to map over your data points if you want decorators on each point
ticks if numberOfTicks has been provided to the chart this array will include the calculated tick values (useful for grids)

This chart does not call a child with the data argument. This is due to the fact that a lot of calculations go into creating the stacked chart, meaning that the original data prop doesn't provide especially valuable information when trying to layout decorators. It does however call with the rest of the common arguments

LineChart

Line chart

Example

import React from 'react'
import { LineChart, Grid } from 'react-native-svg-charts'

class LineChartExample extends React.PureComponent {
    render() {
        const data = [50, 10, 40, 95, -4, -24, 85, 91, 35, 53, -53, 24, 50, -20, -80]

        return (
            <LineChart
                style={{ height: 200 }}
                data={data}
                svg={{ stroke: 'rgb(134, 65, 244)' }}
                contentInset={{ top: 20, bottom: 20 }}
            >
                <Grid />
            </LineChart>
        )
    }
}

Props

See Common Props

Arguments to children

Supports all Common arguments to children

PieChart

The PieChart is a really nice component with great support for custom behavior. See more examples in the examples repo

Pie chart

Example

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} />
    }
}

Props

Property Default Description
data required Very similar to the data prop of our other charts, the only exception is that the PieChart only accepts complex objects (not just numbers). An item can also contain the arc property which allows you two override settings on that specific arc. See examples repo
valueAccessor ({ item }) => item.value Very similar to the yAccessor of the other charts
outerRadius "100%" The outer radius, use this to tweak how close your pie is to the edge of it's container. Takes either percentages or absolute numbers (pixels)
innerRadius "50%" The inner radius, use this to create a donut. Takes either percentages or absolute numbers (pixels)
labelRadius undefined The radius of the circle that will help you layout your labels. Takes either percentages or absolute numbers (pixels)
padAngle The angle between the slices
startAngle 0 The start angle in radians of the entire pie
endAngle Math.PI * 2 The end angle in radians of the entire pie
sort (a,b) => b.value - a.value Like any normal sort function it expects either 0, a positive or negative return value. The arguments are each an object from the dataPoints array

Arguments to children

Property Description
width the width of the canvas in pixels
height the height of the canvas in pixels
slices an array of the pie chart slices. See source code and examples for what it includes
data the same data array provided to the chart, use this to map over your data points if you want decorators on each point

ProgressCircle

Progress circle

Example

import React from 'react'
import { ProgressCircle } from 'react-native-svg-charts'

class ProgressCircleExample extends React.PureComponent {
    render() {
        return <ProgressCircle style={{ height: 200 }} progress={0.7} progressColor={'rgb(134, 65, 244)'} />
    }
}

Props

Property Default Description
progress required PropTypes.number.isRequired
progressColor 'black' PropTypes.any
backgroundColor '#ECECEC' PropTypes.any
startAngle 0 PropTypes.number
endAngle Math.PI * 2 PropTypes.number
strokeWidth 5 PropTypes.number
cornerRadius 45 PropTypes.number

Arguments to children

Property Description
width the width of the canvas in pixels
height the height of the canvas in pixels
data the same data array provided to the chart, use this to map over your data points if you want decorators on each point

YAxis

Y-axis

A helper component to layout your Y-axis labels on the same coordinates as your chart. It's very important that the component has the exact same view bounds (preferably wrapped in the same parent view) as the chart it's supposed to match. If the chart has property contentInset set it's very important that the YAxis has the same vertical contentInset.

Example

import React from 'react'
import { LineChart, YAxis, Grid } from 'react-native-svg-charts'
import { View } from 'react-native'

class YAxisExample extends React.PureComponent {
    render() {
        const data = [50, 10, 40, 95, -4, -24, 85, 91, 35, 53, -53, 24, 50, -20, -80]

        const contentInset = { top: 20, bottom: 20 }

        return (
            <View style={{ height: 200, flexDirection: 'row' }}>
                <YAxis
                    data={data}
                    contentInset={contentInset}
                    svg={{
                        fill: 'grey',
                        fontSize: 10,
                    }}
                    numberOfTicks={10}
                    formatLabel={(value) => `${value}ยบC`}
                />
                <LineChart
                    style={{ flex: 1, marginLeft: 16 }}
                    data={data}
                    svg={{ stroke: 'rgb(134, 65, 244)' }}
                    contentInset={contentInset}
                >
                    <Grid />
                </LineChart>
            </View>
        )
    }
}

Props

(see Common Props)

Property Default Description
scale d3Scale.scaleLinear Should be the same as passed into the charts yScale, or d3Scale.scaleBand if used in conjunction with a horizontal BarChart
svg {} supports all svg props an svg text normally supports
spacingInner 0.05 Spacing between the labels. Only applicable if scale=d3Scale.scaleBand and should then be equal to spacingInner prop on the actual BarChart
spacingOuter 0.05 Spacing outside of the labels. Only applicable if scale=d3Scale.scaleBand and should then be equal to spacingOuter prop on the actual BarChart
formatLabel value => {} A utility function to format the text before it is displayed, e.g `value => "$" + value
contentInset { top: 0, bottom: 0 } Used to sync layout with chart (if same prop used there)
min undefined Used to sync layout with chart (if gridMin is used there)
max undefined Used to sync layout with chart (if gridMax is used there)

Arguments to children

No arguments

XAxis

Line chart

A helper component to layout your X-axis labels on the same coordinates as your chart. It's very important that the component has the exact same view bounds (preferably wrapped in the same parent view) as the chart it's supposed to match. If the chart has property contentInset set it's very important that the XAxis has the same horizontal contentInset.

The XAxis also supports the xAccessor prop, if it's not supplied it will assume that you're only interested in the index of the data set.

Example

import React from 'react'
import { LineChart, XAxis, Grid } from 'react-native-svg-charts'
import { View } from 'react-native'

class XAxisExample extends React.PureComponent {
    render() {
        const data = [50, 10, 40, 95, -4, -24, 85, 91, 35, 53, -53, 24, 50, -20, -80]

        return (
            <View style={{ height: 200, padding: 20 }}>
                <LineChart
                    style={{ flex: 1 }}
                    data={data}
                    gridMin={0}
                    contentInset={{ top: 10, bottom: 10 }}
                    svg={{ stroke: 'rgb(134, 65, 244)' }}
                >
                    <Grid />
                </LineChart>
                <XAxis
                    style={{ marginHorizontal: -10 }}
                    data={data}
                    formatLabel={(value, index) => index}
                    contentInset={{ left: 10, right: 10 }}
                    svg={{ fontSize: 10, fill: 'black' }}
                />
            </View>
        )
    }
}

Props

Property Default Description
data required An array of values or objects to render on the xAxis. Should preferably have the same length as the chart's dataPoints. If a complex object is used instead of a simple value, a xAccessor prop is required to calculate the axis' extent. A data object can contain a svg property which allows you to override styles on that specific object
scale d3Scale.scaleLinear Should be the same as passed into the charts xScale
spacingInner 0.05 Spacing between the labels. Only applicable if scale=d3Scale.scaleBand and should then be equal to spacingInner prop on the actual BarChart
spacingOuter 0.05 Spacing between the labels. Only applicable if scale=d3Scale.scaleBand and should then be equal to spacingOuter prop on the actual BarChart
svg {} Default svg props for all labels. Supports all svg props an svg text normally supports. This styles will be overriden if there are specific styles for a given data object
formatLabel value => value A utility function to format the text before it is displayed, e.g value => "day" + value. Passes back the value provided by the xAccessor
contentInset { left: 0, right: 0 } Used to sync layout with chart (if same prop used there)

Arguments to children

No arguments

Children

New for version 5.0. Each chart (and axes) component now accepts React children. Important note is that all children must be a react-native-svg component on order for it to be rendered by the chart. This API deprecates the old one with extras and decorators. Everything that should be rendered above or below the chart should now be supplied as a child to said chart. This allows you to declare the order in which your decorators should be rendered. If you want anything rendered below the chart, simply add the prop belowChart={true}. There's a ton of examples in the examples repo, go and have a look.

Grid

This library provides a helper component for drawing grids. Simply place it as child to the chart of your choice and (if necessary) set its direction.

Props

Property Default Description
svg {} an object containing all the props that should be passed down to the underlying react-native-svg component. See available props
direction Grid.Direction.HORIZONTAL The direction of the grid lines.
belowChart true whether or not to render below the chart

Examples

There are tons of examples over at react-native-svg-chart-examples

License

MIT

react-native-svg-charts's People

Contributors

aalhaimi avatar alburdette619 avatar andycloke avatar attitude avatar beckywu220 avatar bonno42 avatar christian-athom avatar denieler avatar dependabot[bot] avatar drzigman avatar fqueiruga avatar henebb avatar iammosespaulr avatar jcurtis avatar jesperlekland avatar jyrno42 avatar komkanit avatar koochr avatar krzysztof-miemiec avatar lucaspbordignon avatar martin-adamko avatar mdmitr avatar mgonzalezs avatar mortske avatar narciero avatar roarrain avatar sajikix avatar sprit3dan avatar telmen avatar usrbowe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-svg-charts's Issues

React Native Web compatibility

Is react-native-web compatibility planned? It seems that it should be possible to make this library compatible with both react-native and react-native-web but some work is necessary.

I was able to make it almost work by using webpack aliases:

react-native -> react-native-web
react-native-svg -> svgs

The biggest problem seems to be native only code such as setNativeProps and platform specific files (horizontal-labeled-bar-chart-component.android.jsandhorizontal-labeled-bar-chart-component.ios.js`).

I was able to hack the code quickly to make it render in a browser, so I think it should not take much effort to solve this properly (although I am not very familiar with the project so can't tell for sure)

screen shot 2018-02-14 at 17 09 42

Graph goes to minus rather it haven't minus values

Hi,

My Graph goes to minus. But is haven't any minus values
Please Help...

This is my Code

This is the data valus
[5, 1, 89, 1, 5, 1, 0, 0, 1, 0, 0, 2, 2, 2, 1, 1, 1, 1, 3, 2, 1]

`render() {

let data = this.dataGraph();
console.log("dcscad", data);

const Tooltip = ({ x, y }) => (
  <G
    x={x(this.state.index) - (75 / 2)}
    key={'tooltip'}
    onPress={() => console.log('tooltip clicked')}>
    <G y={0}>
      <Rect
        height={50}
        width={80}
        stroke={''}
        fill={colorsGraph.rectFill}
        ry={10}
        rx={10} />

      {this.renderToolTipText(this.state.value)}

    </G>
    <G x={75 / 2}>
      {/* <Line
            y1={ 50 + 40 }
            y2={ y(data_graph[ 5 ]) }
            stroke={ 'grey' }
            strokeWidth={ 2 }
          /> */}
      <Circle
        cy={y(data[this.state.index])}
        r={6}
        //stroke={colors.primaryColor2}
        //strokeWidth={2}
        fill={colors.primaryColor2}
      />
    </G>
  </G>
);

const chartGraph = () => {
  return (
    <View style={styles.chartScroll}>
      <AreaChart
        style={[styles.chart, { width: this.calculateWidth() }]}
        dataPoints={this.dataGraph()}
        fillColor={colorsGraph.chartFill}
        strokeColor={colors.secondaryColor1}
        contentInset={{ top: 100, bottom: 30, left: 50, right: 50 }}
        extras={this.state.extras}
        renderExtra={({ item, ...args }) => item(args)}
        showGrid={false}
        gridMax={this.state.graphFillHeight} //this is the total of the graph data
        //spacing = {100}
        renderDecorator={({ x, y, index, value }) => (
          <G>
            <Circle
              key={index}
              cx={x(index)}
              cy={y(value)}
              r={4.5}
              stroke={colorsGraph.colorWhite}
              strokeWidth={5}
              fill={colors.secondaryColor1}
              onPress={() => this.setState({ extras: [Tooltip], index: index })}

            />
            <Line
              x1={x(index)}
              y1={"250"}
              x2={x(index)}
              y2={"70"}
              stroke={colorsGraph.chartVerticalGrid}
              strokeWidth="0.3"
            />
          </G>
        )}
      />
      <XAxis
        style={{ }}
        values={this.dataGraphXAxis()}
        formatLabel={value => `${value}`}
        chartType={XAxis.Type.BAR}
        labelStyle={styles.xAxisLable}
        contentInset={{ left: 20, right: 20 }}
      />
    </View>
  );
};



return (
  <View style={styles.container}>
    <ScrollView horizontal={true}>
      {chartGraph()}
    </ScrollView>
    <View>
      <View
        style={styles.chartHorozontalLine} />
      <View>
        <View>
          {this.renderView(this.state.value,this.state.data_type)}
        </View>
      </View>
    </View>
  </View>
  // </MenuContext>
);

}`

following image is the output

graph

Axis labels are rendered overlapping

What is the problem?

XAxis and YAxis labels are not rendering or are being rendered overlapping

When does it happen?

On Render

What platform?

  • [ x] iOS
  • Android (untested)

React Native version: 0.52

Code to reproduce

<YAxis
  data={[50,10,40,95]}
  svg={{ fontSize: 8, fill: 'grey' }}
  style={[{ flex: 1, width: 50 }]}

XAxis - No display

I've followed your example in XAxis, but it doesn't display anything. All I get was a padding in bottom.

Render values at the center of the pie.

Hello.
First, thanks for your awesome library.
I like to render the title and value of the chosen slice at the center, something like this:
screenshot from 2018-03-07 12-26-04

I've looked for a prop or something else to do it, but I didn't succeed.
Do you have any idea for me? Tnx.

Is it possible to animate ECG animation to the Line chart?

Firstly I just want to say you guys are doing a great job and I'm grateful for finding this library.

I had a question regarding the animation. You see my situation is the following:

I have an app that Receives data from an external device. What I'd like to do is visualize the data in line graph.

The main issue, we cant use CSS animation and CSS keyframes, this makes it hard for the animation of the line.

For example, suppose this is the data I receive from an external device:

var _data = [
  0, 0, 0, 0, 0.0000050048828125, 0.0000137939453125, 0.000049560546875,
  0.00008740234375, 0.00015966796875, 0.000262451171875, 0.0003975830078125, 0.0005687255859375,
  0.0007802734375, 0.001037353515625, 0.0013468017578125, 0.00172119140625, 0.0021756591796875,
  0.0027232666015625, 0.0033880615234375, 0.004206787109375, 0.0052380371093750005,
  0.006586181640625, 0.008400146484375001, 0.010904296875, 0.0144892578125, 0.0196798095703125,
  0.049684204101562504, 0.0886883544921875, 0.11185363769531251, 0.134164306640625,
  0.137352294921875, 0.1160369873046875, 0.08516308593750001, 0.0539765625,
  0.014997436523437501, -0.015882568359375, -0.0387554931640625, -0.06125732421875, -0.0745780029296875, -0.07479357910156251, -0.0725338134765625, -0.0418538818359375,
  0.08582861328125001, 0.397717529296875, 0.8136408691406251, 1.2295617980957032,
  0.9944150390625001, 0.2824605712890625, -0.38949267578125, -0.597251220703125, -0.425675537109375, -0.1537947998046875, -0.0500914306640625, -0.0111041259765625,
  0.0027451171875, 0.0071739501953125, 0.008443359375, 0.0094327392578125, 0.012530517578125,
  0.0176046142578125, 0.0300162353515625, 0.0433489990234375, 0.056962646484375004,
  0.0704832763671875, 0.0770511474609375, 0.0898175048828125, 0.10311853027343751,
  0.117046142578125, 0.1312630615234375, 0.1529300537109375, 0.167607177734375,
  0.1899068603515625, 0.2124422607421875, 0.235044677734375, 0.2575535888671875,
  0.2724073486328125, 0.286978271484375, 0.3007579345703125, 0.3067425537109375,
  0.3106370849609375, 0.303756103515625, 0.2897236328125, 0.25916931152343753,
  0.2200599365234375, 0.1728209228515625, 0.133416259765625, 0.086224853515625,
  0.05493408203125, 0.02409423828125, 0.00922607421875, -0.0043409423828125, -0.0097349853515625, -0.013127685546875, -0.01423095703125, -0.013834716796875, -0.012556030273437501, -0.010675048828125, -0.00835888671875, -0.0057305908203125, -0.0000562744140625
];

I want to be able to make it readable using line animation: ECG Animation.

Note that the example is using d3 library.

Thanks guys!

Stacked Line Chart

Hi, is it possible to draw multiple LineCharts over each other? I'm currently trying to do something of the sort but can't get it to work. Is it possible to draw multiple lines with LineChart or will I need something like a StackedLineChart? (Which does not currently exist)

Customize styles for each of the axises items.

In our project we need to customize the axis item styles indivitually on a chart. AFAIK, the axis only allows setting styles for all the items at once.

What I'm trying to achieve (:
multicoloraxis

I think a nice solution for this would be making the svg prop on the XAxis and YAxis components to also accept a function. This function would be called with the value and index arguments, same as the formatLabel prop, and would return an object with the styles. This approach wouldn't break backwards compatibility.

Sample code:

    <XAxis
            data={data}
            formatLabel={this.formatDayLabel}
            svg={(value, index) => ({
              fontSize: 10,
              fontWeight: index < data.length - 1 ? 'normal' : 'bold',
              fill: index < data.length - 1 ? Color.AXIS_GREY : Color.AXIS_BLUE,
            })}
            scale={scale.scaleBand}
            spacing={0.5}
            />

The implementation could be something like this (on the XAxis component:

    <SVGText
                  textAnchor={'middle'}
                  originX={x(value)}
                  alignmentBaseline={'hanging'}
                  {...(svg instanceof Function ? svg(value, index) : svg)}
                  key={index}
                  x={x(value)}
                >
                  {formatLabel(value, index)}
                </SVGText>

I understand this approach could not be ideal and coherent if it isn't used in all the other components. Another solution would be creating another prop without altering the svg prop.

I'd love to contribute and implement this solution and expanding the docs if you like this approach.

Layered LineChart with X & Y Axis

What is the problem?

I can't get the LineCharts to overlap correctly. You will see the gradient colour line is positioned correctly, however I can't get the white line to overlap correctly. I suspect it has something to do with the "StyleSheet.absoluteFill", have tried various style props but can't get it to work.

When does it happen?

What platform?

  • iOS
  • Android

react-native-cli: 2.0.1
react-native: 0.53.0

Code to reproduce

import React from 'react'
import { Defs, LinearGradient, Path, Stop } from 'react-native-svg'
import { LineChart, XAxis, YAxis } from 'react-native-svg-charts'
import { StyleSheet, View } from 'react-native'

class GradientLineExample extends React.PureComponent {

  render() {

    const xData = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
    const yData = [ 1000, 800, 600, 400, 200, 0]
    const data = [ 900, 780, 540, 420, 420, 460, 920, 420, 420, 420, 420, 420 ]
    const data2 = [ 900, 780, 540, 420, 420, 460, 920, 420, 420, 420, 420, 420 ].reverse()

    const Gradient = () => (
      <Defs key={'gradient'}>
        <LinearGradient id={'gradient'} x1={'0'} y={'0%'} x2={'100%'} y2={'0%'}>
          <Stop offset={'0%'} stopColor={'rgb(134, 65, 244)'}/>
          <Stop offset={'100%'} stopColor={'rgb(66, 194, 244)'}/>
        </LinearGradient>
      </Defs>
    )

    const Shadow = ({ line }) => (
      <Path
        key={'shadow'}
        y={2}
        d={line}
        fill={'none'}
        strokeWidth={4}
        stroke={'rgba(134, 65, 244, 0.2)'}
      />
    )

    const contentInset = { top: 20, bottom: 20 }

    return (
      <View>
      <View style={ { height: 200, flexDirection: 'row', paddingHorizontal: 20 } }>
        <YAxis
          data={yData}
          contentInset={ contentInset }
          svg={{
              fill: 'white',
              fontSize: 10,
          }}
          numberOfTicks={6}
          formatLabel={ (value) => `${value}K` }
        />
        <LineChart
          style={ { flex: 1 } }
          data={ data }
          gridMax={0}
          gridMin={-0}
          contentInset={ contentInset }
          svg={{
            strokeWidth: 2,
            stroke: 'url(#gradient)',
          }}
          numberOfTicks={12}
          extras={[ Gradient, Shadow ]}
        />
        <LineChart
          style={ StyleSheet.absoluteFill }
          gridMax={0}
          gridMin={-0}
          data={ data2 }
          contentInset={ { top: 20, bottom: 20 } }
          svg={{
            strokeWidth: 2,
            stroke: 'white',
          }}
          numberOfTicks={12}
          extras={[ Gradient, Shadow ]}
        />
      </View>
      <XAxis
        style={{ marginHorizontal: -10, paddingHorizontal: 20, marginLeft: 20 }}
        data={ xData }
        formatLabel={ (value) => xData[value] }
        contentInset={{ left: 20, right: 20 }}
        numberOfTicks={12}
        svg={{ 
          fill: 'white', 
          fontSize: 10 
        }}
      />
      </View>
    )
  }
}

export default GradientLineExample

Screenshot:

simulator screen shot - iphone 6 - 2018-03-01 at 16 17 07

Instructions for sample app are not working

What is the problem?

I followed the instruction to get the sample app running and it did not work. I'm getting a "No bundleURL present" error in the simulator.

Googling the error seem to point toward the need to upgrade react native. The package still includes 0.46 when the current version is 0.53.

When does it happen?

Follow instruction in readme
the only difference is I'm using the version of reacting native installed in the node_mobulde directory:
./node_modules/.bin/react-native run-ios

What platform?

  • iOS iphone 8 ios 11.2 simulator
  • Android

React Native version: 0.46.0 (installed via the command yarn on the project)

Define a value from which the yAxis should start.

What is the problem?

yAxis always starts from 0 and that create a useless area under the chart, if all the values are bigger than 0.

When does it happen?

I have a chart with values 20.000ยฑ200.
The chart is rendered correctly but I would like yAxis to start from 19.000 instead of 0.

What platform?

  • iOS
  • Android

React Native version: 0.49

Code to reproduce

<AreaChart
    style={{ flex: 1 }}
    dataPoints={performance}
    contentInset={{ top: 10, bottom: 10, left: 10, right: 10 }}
    curve={shape.curveNatural}
    svg={{
    fill: 'rgba(134, 65, 244, 0.2)',
    stroke: 'rgb(134, 65, 244)',
    }}
/>

screenshot_1516813945

Thank you in advance :)

Any plans to support scaleTime

Do you have plans to support d3.scaleTime for time series data. Would be a useful addition to this very useful module.

XAxis rotate labels

Due to the ordering of styles on labels, it is not possible to set transformations. They are overriden by the internals.

In our case we would like to rotate the text labels to have more space for its contents.

Have a look here:

What do you think, would it make sense to reorder the attributes? Or at least to not return an empty array, but null / undefined. I think this would be than ignored and would only break transforms on PIE charts.

Different color for each bar in a bar chart;

What is the problem?

Warning: Failed prop type: Invalid prop โ€˜fillโ€˜ of type โ€˜arrayโ€˜ supplied to โ€˜AnimatedPathโ€˜, expected โ€˜stringโ€˜.

When does it happen?

const barData = [
{
values: [10,20,40],
positive: {
fill: ["#a7d4fb", "#a7d4fc", "#a7d4fd"]
// warning Happens at this points...i was trying fill different color for each bar
}
}
];

What platform?

  • Android -->26.0.2

"dependencies": {
"react": "16.0.0",
"react-native": "0.51.1",
"react-native-svg": "^6.2.1"
}

Stacktrace (if crash)

Warning: Failed prop type: Invalid prop โ€˜fillโ€˜ of type โ€˜arrayโ€˜ supplied to โ€˜AnimatedPathโ€˜, expected โ€˜stringโ€˜.

in AnimatedPath (at bar-chart.js:157)

in BarChart (at App .:1s 96)

in RCTView (at View. 13: 1 12)

in View (at App .:1s 94)

in RCTView (at View .:1s 112)

in View (at App' .:1s 68)

in RCTView (at View. 13: 112)

in View (at ScrollView.js:748)

in RCTScrollView (at ScrollView.jsz857)

in ScrollView (at App' .:1s 67)

in RCTView (at View. 13: 112)

in View (at App .15: 66)

in App (at renderApplication.js:35) in RCTView (at View.js:1 12)

in View (at AppContainer.js:102) in RCTView (at View.js:1 12) in View (at AppContainer.js:122)

in AppContainer (at renderApplication.js: 34)

Different inner/outer radius for piechart?

First of all, thank you for the library. It's awesome. I've been using it for making charts on my react-native applications.
I was just wondering if there is any way to have different inner/outer radius in piechart for different data point?

No component found for view with name 'RNSVGPath'

I'm getting this error, after installing, linking and running

<ProgressCircle
    style={ { height: 200 } }
    progress={ 0.7 }
    progressColor={'rgb(134, 65, 244)'}
/>

React Native: 0.51
svg: 6.0.1-rc.3
svg-charts: 2.1.0

simulator screen shot - iphone 6 - 2018-01-19 at 12 56 42

onPress event on circle decorator

Hi,

Need a event on circle click, that has to show tool tip on circle click dynamically.
Please help to do that

Like this

<View style={styles.chartScroll}>
        <AreaChart
          style={this.chartStyle()}
          dataPoints={this.dataGraph()}
          fillColor={colorsGraph.chartFill}
          strokeColor={colors.secondaryColor1}
          contentInset={{top: 50, bottom: 30, left: 50, right: 50 }}
          extras={[Tooltip]}
          renderExtra={({ item, ...args }) => item(args)}
          showGrid={false}
          gridMax={150}
          //spacing = {100}
          renderDecorator={({ x, y, index, value }) => (
            <G>
              <Circle
                key={index}
                cx={x(index)}
                cy={y(value)}
                r={4}
                //stroke={ 'rgb(134, 65, 244)' }
                fill={colors.secondaryColor1}
                onPress={() => this.someFunction()}////////////////////////////////////////// this is the function
/////then have to show tool tip in each circle click and have to show the value

              />
              <Line
                x1={x(index)}
                y1={"250"}
                x2={x(index)}
                y2={"70"}
                stroke={colorsGraph.chartVerticalGrid}
                strokeWidth="0.3"
              />
            </G>
          )}
        />
        <XAxis
          style={{ paddingVertical: 0 }}
          values={this.dataGraph()}
          formatLabel={value => `${value}`}
          chartType={XAxis.Type.BAR}
          labelStyle={{color:'black'}}
          contentInset={{ left: 20, right: 20 }}
        />
      </View>

is there way to do that....Please help....

Gradient Line for Area chart

Hi,
How can I make the line gradient for Area charts?
renderGradient only effects the area. I also want the line to have gradient effect.

PieChart, allow onPress of each pie piece.

Is it possible to be able to apply onPress events to each piece of the pie ?

I added an onPress to the Circle label.. however I am not sure how to do make the entire piece touchable

Stacked bar chart - horizontal support?

Is there support for rendering the stacked bar charts horizontally? Not sure if this is a user problem (i.e. me) or it's just not supported. I suspect the latter because I don't see anything in the js for that chart type that looks like a horizontal property.

On the other hand, I've been unable to adapt the horizontal line extra (https://github.com/JesperLekland/react-native-svg-charts-examples/blob/master/storybook/stories/extras.js) to this chart and it does appear to be calling renderExtra which makes me think I'm doing something wrong.

I was hoping I could just look at the changes made for the bar chart but I found this in the PR:

BarChart has been rewritten from the ground up

:) Guess I'm going to have to figure it out the hard way now...

render 2 line charts into 1 chart?

is there a way to render 2 line charts in 1 chart?
I want to merge these 2 line charts to 1 chart

and also render another Yaxis to the right of the merged chart.
------------------
------------------
------------------
Yaxis1 Yaxis2

charts

Touch support

Hi,

Is touch support, e.g clicking datapoints and/or zooming in graphs, something that's planned for a future? Would be fantastic!

Two colors same graph

Hello,

I'm having some trouble putting two colors on the same chart like this image:

screen shot 2018-03-01 at 8 56 09 am
Does anyone have an idea of how can I do so?

Thank you,
Sofiane.

Charts not rendering

What is the problem?

Using various examples (I only tried AreaChart and LineChart) in Expo don't render.

StackedAreaChart doesn't properly render all data points

What is the problem?

StackedAreaChart doesn't properly render all the data points. In particular, it only renders the first keys.length data points.

When does it happen?

The following code should render a StackedAreaChart that looks like the one from the examples, but with one additional data point (making five total).

class StackedAreaExample extends React.PureComponent {

    render() {

        const data = [
            {
                month: new Date(2015, 0, 1),
                apples: 3840,
                bananas: 1920,
                cherries: 960,
                dates: 400,
            },
            {
                month: new Date(2015, 1, 1),
                apples: 1600,
                bananas: 1440,
                cherries: 960,
                dates: 400,
            },
            {
                month: new Date(2015, 2, 1),
                apples: 640,
                bananas: 960,
                cherries: 3640,
                dates: 400,
            },
            {
                month: new Date(2015, 3, 1),
                apples: 3320,
                bananas: 480,
                cherries: 640,
                dates: 400,
            },
            {
                month: new Date(2015, 4, 1),
                apples: 2320,
                bananas: 780,
                cherries: 440,
                dates: 400,
            },
        ]

        const colors = [ '#ED5314', '#FFB92A', '#FEEB51', '#9BCA3E' ]
        const keys   = [ 'apples', 'bananas', 'cherries', 'dates' ]

        return (
            <StackedAreaChart
                style={ { height: 200, paddingVertical: 16 } }
                data={ data }
                keys={ keys }
                colors={ colors }
                curve={ shape.curveNatural }
                showGrid={ false }
            />
        )
    }
}

However, this code only renders the first four data points.

What platform?

Occurs on both iOS and Android platforms.

Additional comments

I think the problem has something to do with this line, which seems to be using keys.length when it should be using data.length. However, changing that line alone does not fix the issue, so there must be another place where the number of data points is being calculated incorrectly.

Support for data of different length in StackedAreaChart?

What is the problem?

StackedAreaChart accepts an array of objects, in which all datapoints are specified by keys. I have a use-case where I have two separate "timelines", where I want to show data from two data-sets that dont necessarily have the same length.

For example, I have one chart with data points + timestamps, and I want to display this along with another set of datapoints with different timestamps.

One solution would be to inject the second set into the first one based on the "closest" timestamp for each value, but this doesn't seem like a good solution.

Could StackedAreaChart support datasets of different length?

Lets say I want to show amount of page visits for a page, in correlation with how many times a topic is mentioned on Twitter:

// Page visits per hour
const pageVisits = [
  { visits: 149, timestamp: 1518388122 },
  { visits: 123, timestamp: 1518391722 },
  { visits: 180, timestamp: 1518395322 },
  { visits: 190, timestamp: 1518398922 },
  { visits: 430, timestamp: 1518402502 },
  { visits: 614, timestamp: 1518406522 },
  { visits: 590, timestamp: 1518409722 },
  { visits: 301, timestamp: 1518413322 },
  { visits: 159, timestamp: 1518416922 },
  { visits: 140, timestamp: 1518420522 },
]

// Mentions for a topic on Twitter
const mentions = [
  { mentions: 3, timestamp: 1518389240 },
  { mentions: 2, timestamp: 1518394852 },
  { mentions: 3, timestamp: 1518398495 },
  { mentions: 45, timestamp: 1518402853 },
  { mentions: 87, timestamp: 1518405495 },
  { mentions: 120, timestamp: 1518408928 },
  { mentions: 90, timestamp: 15184135032 }
]

Would it be possible to show two charts with different datapoints but along the same "timeline" on top of each other?

What platform?

  • iOS
  • Android

XAxis formatLabel not showing value

Hey.

I'm stuck with the formatLabel prop. I want to show the date under my chart. Now it just shows the array key.

This is the array that gets returned by the this._chartXAxis() function:

["2018-02-20", "2018-02-21", "2018-02-22", "2018-02-23", "2018-02-24", "2018-02-25", "2018-02-26", "2018-02-27"]

image

Here's my code:

<View style={styles.chartContainer}>
    <Card>
        <View style={styles.chart}>
            <LineChart
                style={{ flex: 1 }}
                data={this._chartStats('impressions')}
                gridMin={0}
                svg={{ stroke: '#969FAD' }}
                contentInset={{ top: 10, bottom: 10 }}
            />
            <LineChart
                style={ StyleSheet.absoluteFill }
                data={this._chartStats('clicks')}
                gridMin={0}
                svg={{ stroke: '#1E92FF' }}
                contentInset={{ top: 10, bottom: 10 }}
            />
            <LineChart
                style={ StyleSheet.absoluteFill }
                data={this._chartStats('payout')}
                gridMin={0}
                svg={{ stroke: '#FE2851' }}
                contentInset={{ top: 10, bottom: 10 }}
            />
            <LineChart
                style={ StyleSheet.absoluteFill }
                data={this._chartStats('conversions')}
                gridMin={0}
                svg={{ stroke: '#FE2851' }}
                contentInset={{ top: 10, bottom: 10 }}
            />
            <LineChart
                style={ StyleSheet.absoluteFill }
                data={this._chartStats('payout')}
                gridMin={0}
                svg={{ stroke: '#44DB5E' }}
                contentInset={{ top: 10, bottom: 10 }}
            />
            <XAxis
                style={{ marginHorizontal: -10 }}
                data={ this._chartXAxis() }
                formatLabel={(value, index) => value}
                contentInset={{ left: 10, right: 10 }}
                svg={{ fontSize: 10 }}
            />
        </View>
    </Card>
</View>

extras not rendered with ProgressCircle

What is the problem?

Your extras example works great for the LineChart, but when I try a similar example with a ProgressCirle, I can't get any extras to render. I'm trying to render in the center of the progress circle.

When does it happen?

When trying to render a ProgressCircle with a extra. The same extra works fine with a LineChart.

What platform?

  • iOS 11.2 (iPad Simulator)

React Native version: 0.51.0

Code to reproduce

import React from 'react'
import { ProgressCircle } from 'react-native-svg-charts'
import { Text } from 'react-native-svg'

class Home extends React.PureComponent {
    render() {

        const chartLabel = () => (
            <Text
              key={ 'label' }
              x={ '50%' }
              y={ '50%' }>
              My Label
            </Text>
        )

        return (
          <ProgressCircle
              style={ { height: 200 } }
              progress={ 0.7 }
              progressColor={ 'rgb(134, 65, 244)' }
              startAngle={ -Math.PI * 0.8 }
              endAngle={ Math.PI * 0.8 }
              extras={ [ chartLabel ] }
              renderExtra={ ({ item, ...args }) => item(args) }
            />
        )
    }
}

export default Home;

Again, very similar code works fine for a LineChart, rendering the label in the center of the chart:

import React from 'react'
import { LineChart } from 'react-native-svg-charts'
import { Text } from 'react-native-svg'
import * as shape from 'd3-shape'

class Home extends React.PureComponent {

    render() {

      const data = [ 50, 10, 40, 95, -4, -24, 85, 91, 35, 53, -53, 24, 50, -20, -80 ]

      const chartLabel = () => (
          <Text
            key={ 'label' }
            x={ '50%' }
            y={ '50%' }>
            My Label
          </Text>
      )

      return (
        <LineChart
            style={ { height: 200 } }
            dataPoints={ data }
            svg={{
                fill: 'purple',
                stroke: 'rgb(134, 65, 244)',
                strokeWidth: 2,
            }}
            shadowSvg={{
                stroke: 'rgba(134, 65, 244, 0.2)',
                strokeWidth: 5,
            }}
            contentInset={ { top: 20, bottom: 20 } }
            curve={ shape.curveLinear }
            extras={ [ chartLabel ] }
            renderExtra={ ({ item, ...args }) => item(args) }
          />
      )
    }
}

export default Home;

How to show Vertical Lines?

What is the problem?

I'm not sure if this is just something not implemented in this library or if I've missed something in the README. How do I get my charts to render vertical grid lines, and not horizontal ones? By default only horizontal ones are rendered and while there exists a showGrid function this only hides horizontal grid lines.

(edit: I'm fairly new to charting libraries as a whole!)

Animate progress - ProgressCircle

Hello!

I'm using the animate and the animateDuration prop with a ProgressCircle.
Right now the result of this is that the ProgressCircle scales up from small to large during the duration.

Is there a way to animate the progress instead so the progress 'fills' up to the desired progress over the duration?

Cool library by the way!

Error while updating property 'd' in shadow node

What is the problem?

Unable to set the value of barchart to 0 which causes me to give below error.

screenshot_2018-03-07-20-12-30 1

When does it happen?

import React from 'react'
import { BarChart } from 'react-native-svg-charts'
import { Defs, LinearGradient, Stop } from "react-native-svg";

class ColorBarExample extends React.PureComponent {

    render() {

        const barDataCritical = [
      {
        value:0,
      },
      {
        value: 0, **// ERROR HAPPPENS WHEN I SET VALUE TO 0**
        svg: {
          fill: 'rgb(226, 225, 223)',
        },
      },
      {
        value: 3,
        svg: {
          fill: 'rgb(239, 203, 133)',
        },
      },
    ];

        return (
            <BarChart
                style={{ height: 200 }}
                data={barDataCritical}
                gridMin={0}
                svg={{ fill: 'rgba(134, 65, 244, 0.8)' }}
                yAccessor={({ item }) => item.value}
                contentInset={{ top: 20, bottom: 20 }}
            />
        )
    }

}

export default ColorBarExample

I'm using these Barchart

What platform?

"react": "16.1.0",
"react-native": "0.54.0",
"react-native-svg": "^6.2.2",
"react-native-svg-charts": "^4.0.0",
"react-native-vector-icons": "^4.5.0"

Horizontal BarChart

Any easy way out to create horizontal bar charts with x-axis (which would eventually look like the y)?

Linechart on extra is not rendering on android

Rendering a linechart chart, in extra prop of barchart, does not work on android, but, it works fine on ios.

Has anyone seen this behaviour before and knows how to solve? Thanks!

  • iOS
  • Android

React Native version: 0.48.4

Code to reproduce

renderLineChart(data, contentInset = {}, chart, shadow=true){
        return (
            <LineChart
                key={data[0]}
                style={{ flex: 1 }}
                dataPoints={ data }
                svg={ {
                    stroke: '#2196F3',
                    strokeWidth: 3
                } }
                shadowSvg={ {
                    stroke: shadow ? 'rgba(0,0,0, 0.1)' : 'transparent',
                    strokeWidth: 5,
                    y: 3
                } }
                shadowColor={ 'rgba(0,0,0, 0.1)' }
                curve={shape.curveLinear}
                contentInset={contentInset}
                showGrid={false}
                extras={ [(axis) => data.map((item,index) => this.Tooltip(axis, {item, index}, chart, _.max(data)))]  }
                renderExtra={ ({ item, ...args }) => item(args) }
            />
        )
    }

Tooltip = ({ x, y }, {item, index}, chart, maxData = 0, color='#2196F3') => {
        return this.state.showTooltip[chart] === index ? 
            <G
                x={ x(index) - (75 / 2) }
                key={ index }
                onPress={ () => {
                    let { showTooltip } = this.state;
                    showTooltip = [ ... INITAL_TOOLTIP_VALUE];
                    this.setState({ showTooltip });
                }}
            >
                <G y={ y(item) + (item / maxData > 0.7 || (item == 0 && maxData < 5) ? 30 : -70) } x={ index == 5 ? - 40 : (index == 0 ? 40 : 0) } style={{ zIndex: 9999 }}>
                    <Rect
                        height={ 40 }
                        width={ 75 }
                        stroke={ 'grey' }
                        fill={ 'white' }
                        ry={ 10 }
                        rx={ 10 }
                    />
                    <SvgText
                        x={ 75 / 2 }
                        textAnchor={ 'middle' }
                        y={ 10 }
                        stroke={ color }
                    >
                        {`${item}`}
                    </SvgText>
                </G>
                <G x={ 75 / 2 }>
                    <Line
                        y1={ y(item) + (item / maxData >= 0.7 || (item == 0 && maxData < 5)  ? 30 : -30)  }
                        y2={ y( item ) }
                        x1={ index == 5 ? - 40 : (index == 0 ? 40 : 0)  }
                        x2={index}
                        stroke={ 'grey' }
                        strokeWidth={ 2 }
                    />
                    <Circle
                        cy={ y( item ) }
                        r={ 10 }
                        stroke={ color }
                        strokeWidth={2}
                        fill={ 'white' }
                    />
                </G>
            </G> :   
            <G
                x={ x(index) }
                key={ index }
                onPress={ () => {
                    let { showTooltip } = this.state;
                    showTooltip = [ ... INITAL_TOOLTIP_VALUE];
                    showTooltip[chart] = index;
                    this.setState({ showTooltip });
                }}
            >
                <Circle
                    cy={ y( item ) }
                    r={ 30 }
                    stroke={ 'transparent' }
                    strokeWidth={2}
                    fill={ 'transparent' }
                />
            </G>
            ;
    }

render() {
  return(
    <Card>
                            <Text style={[styles.cardHeaderText, { color: '#000', fontSize: 18 }]}>Grow x Churn</Text>
                            <Text style={styles.cardSubHeaderText}>รšltimos 6 meses</Text>
                            <View style={ { height: 250, flexDirection: 'row' } }>
                                <YAxis
                                    dataPoints={ growChurn }
                                    contentInset={ { top: 10, bottom: -10 } }
                                    labelStyle={ { color: 'grey' } }
                                    formatLabel={ value => value }
                                    numberOfTicks={6}
                                />
                                <BarChart
                                    style={ { flex: 1, marginLeft: 20, marginTop: 20 } }
                                    data={[{
                                        values: growChurn,
                                        positive: {
                                           fill: '#00C853'
                                        },
                                        negative: {
                                           fill: '#ef5350',
                                           x: android ? -22.5 : -24
                                        }
                                    }]}
                                    contentInset={{ right: -24 }}
                                    numberOfTicks={6}
                                    extras={ [() => this.renderLineChart(liquido, { bottom: 10 }, 1)] }
                                    renderExtra={ ({ item, ...args }) => item(args) }
                                    gridMax={_.max(growChurn)}
                                />
                            </View>
                            <XAxis
                                style={ { paddingBottom: 16, top: 10, marginLeft: 55, marginRight: 12 } }
                                values={ months }
                                contentInset={{right: 10, left: 10}}
                                formatLabel={ (value, index) => value }
                                chartType={ XAxis.Type.LINE }
                                labelStyle={ { color: 'grey' } }
                            />
                        </Card>
  );
}

extras and renderExtra in StackedAreaChart.

Hi Jesper,

whatโ€™s the purpose of extras and renderExtra in StackedAreaChart?

I understand concept in other charts, there are only extras, which can contain render routines, but I donโ€™t understand what intention you have addressed with this map.
{ extras.map((item, index) => renderExtra({ item, x, y, index, width, height })) }

Could you just point please a case when this can be handy.

Thanks for answer.

Android: not working RNSVGLine

What is the problem?

Android: Error while updating property 'strokeWidth' in shadow node of type: RNSVGLine #583
TypeError: expected dynamic type double, but had type string

When does it happen?

What platform?

  • iOS
  • Android
    I was working on Expo version 24.0.0 It uses "react-native-svg-charts": "^2.1.0",
    IOS working fine

Code to reproduce

![35194523-fc730914-feda-11e7-8c4b-d356af6ee276](https://user-images.githubusercontent.com/12689764/35909846-5a9926be-0c27-11e8-8f49-865aa29f8982.jpg)
<AreaChart
                        style={{ height: 200 }}
                        dataPoints={this.state.charts}
                        contentInset={ { top: 30, bottom: 30 } }
                        curve={shape.curveNatural}
                        svg={{
                            fill: 'rgba(134, 65, 244, 0.2)',
                            stroke: 'rgb(134, 65, 244)',
                        }}
                    />

Support for raster <Image /> in "PieChart with label"?

Hi there. Thanks for this awesome library!

I'm trying to place .png images into the circular labels, is this supported?

Here's my code so far:

<PieChart
  style={{ height: 240 }}
  data={pieData}
  spacing={0}
  innerRadius={16 * 2.75}
  outerRadius={16 * 3}
  labelRadius={16 * 6}
  renderDecorator={({ item, pieCentroid, labelCentroid, index }) => (
    <G key={index}>
      <Line
        x1={labelCentroid[0]}
        y1={labelCentroid[1]}
        x2={pieCentroid[0]}
        y2={pieCentroid[1]}
        stroke={item.color}
        strokeWidth={2}
      />
      <Circle
        cx={labelCentroid[0]}
        cy={labelCentroid[1]}
        r={18}
        fill={item.color}
      />
      <Image
        x={0}
        y={0}
        width={15}
        height={15}
        preserveAspectRatio="xMidYMid slice"
        opacity="1"
        href={require('../assets/images/logo.png')}
        strokeWidth={2}
      />
    </G>
  )}
/>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.