Giter Site home page Giter Site logo

indiespirit / react-native-chart-kit Goto Github PK

View Code? Open in Web Editor NEW
2.7K 13.0 647.0 2.27 MB

📊React Native Chart Kit: Line Chart, Bezier Line Chart, Progress Ring, Bar chart, Pie chart, Contribution graph (heatmap)

Home Page: https://expo.io/@indiespirit/react-native-chart-kit

License: MIT License

JavaScript 13.11% TypeScript 86.89%
chart chart-kit react-native expo react-native-charts react-native-graphs

react-native-chart-kit's Introduction

If you're looking to build a website or a cross-platform mobile app – we will be happy to help you! Send a note to [email protected] and we will be in touch with you shortly.

Chart Kit

📲See example app

To try the examples in Expo, please change main to ./node_modules/expo/AppEntry.js in package.json before starting things with expo run. You'll need to have expo-cli installed via npm install -g expo-cli.

React Native Chart Kit Documentation

Import components

  1. yarn add react-native-chart-kit
  2. yarn add react-native-svg install peer dependencies
  3. Use with ES6 syntax to import components
import {
  LineChart,
  BarChart,
  PieChart,
  ProgressChart,
  ContributionGraph,
  StackedBarChart
} from "react-native-chart-kit";

Quick Example

<View>
  <Text>Bezier Line Chart</Text>
  <LineChart
    data={{
      labels: ["January", "February", "March", "April", "May", "June"],
      datasets: [
        {
          data: [
            Math.random() * 100,
            Math.random() * 100,
            Math.random() * 100,
            Math.random() * 100,
            Math.random() * 100,
            Math.random() * 100
          ]
        }
      ]
    }}
    width={Dimensions.get("window").width} // from react-native
    height={220}
    yAxisLabel="$"
    yAxisSuffix="k"
    yAxisInterval={1} // optional, defaults to 1
    chartConfig={{
      backgroundColor: "#e26a00",
      backgroundGradientFrom: "#fb8c00",
      backgroundGradientTo: "#ffa726",
      decimalPlaces: 2, // optional, defaults to 2dp
      color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
      labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
      style: {
        borderRadius: 16
      },
      propsForDots: {
        r: "6",
        strokeWidth: "2",
        stroke: "#ffa726"
      }
    }}
    bezier
    style={{
      marginVertical: 8,
      borderRadius: 16
    }}
  />
</View>

Chart style object

Define a chart style object with following properies as such:

const chartConfig = {
  backgroundGradientFrom: "#1E2923",
  backgroundGradientFromOpacity: 0,
  backgroundGradientTo: "#08130D",
  backgroundGradientToOpacity: 0.5,
  color: (opacity = 1) => `rgba(26, 255, 146, ${opacity})`,
  strokeWidth: 2, // optional, default 3
  barPercentage: 0.5,
  useShadowColorFromDataset: false // optional
};
Property Type Description
backgroundGradientFrom string Defines the first color in the linear gradient of a chart's background
backgroundGradientFromOpacity Number Defines the first color opacity in the linear gradient of a chart's background
backgroundGradientTo string Defines the second color in the linear gradient of a chart's background
backgroundGradientToOpacity Number Defines the second color opacity in the linear gradient of a chart's background
fillShadowGradientFrom string Defines the first color in the linear gradient of the area under data (can also be specified as fillShadowGradient)
fillShadowGradientFromOpacity Number Defines the first color opacity in the linear gradient of the area under data (can also be specified as fillShadowGradientOpacity)
fillShadowGradientFromOffset Number Defines the first color offset (0-1) in the linear gradient of the area under data
fillShadowGradientTo string Defines the second color in the linear gradient of the area under data
fillShadowGradientToOpacity Number Defines the second color opacity in the linear gradient of the area under data
fillShadowGradientToOffset Number Defines the second color offset (0-1) in the linear gradient of the area under data
useShadowColorFromDataset Boolean Defines the option to use color from dataset to each chart data. Default is false
color function => string Defines the base color function that is used to calculate colors of labels and sectors used in a chart
strokeWidth Number Defines the base stroke width in a chart
barPercentage Number Defines the percent (0-1) of the available width each bar width in a chart
barRadius Number Defines the radius of each bar
propsForBackgroundLines props Override styles of the background lines, refer to react-native-svg's Line documentation
propsForLabels props Override styles of the labels, refer to react-native-svg's Text documentation
propsForVerticalLabels props Override styles of vertical labels, refer to react-native-svg's Text documentation
propsForHorizontalLabels props Override styles of horizontal labels, refer to react-native-svg's Text documentation

Responsive charts

To render a responsive chart, use Dimensions react-native library to get the width of the screen of your device like such

import { Dimensions } from "react-native";
const screenWidth = Dimensions.get("window").width;

Line Chart

Line Chart

const data = {
  labels: ["January", "February", "March", "April", "May", "June"],
  datasets: [
    {
      data: [20, 45, 28, 80, 99, 43],
      color: (opacity = 1) => `rgba(134, 65, 244, ${opacity})`, // optional
      strokeWidth: 2 // optional
    }
  ],
  legend: ["Rainy Days"] // optional
};
<LineChart
  data={data}
  width={screenWidth}
  height={220}
  chartConfig={chartConfig}
/>
Property Type Description
data Object Data for the chart - see example above
width Number Width of the chart, use 'Dimensions' library to get the width of your screen for responsive
height Number Height of the chart
withDots boolean Show dots on the line - default: True
withShadow boolean Show shadow for line - default: True
withInnerLines boolean Show inner dashed lines - default: True
withOuterLines boolean Show outer dashed lines - default: True
withVerticalLines boolean Show vertical lines - default: True
withHorizontalLines boolean Show horizontal lines - default: True
withVerticalLabels boolean Show vertical labels - default: True
withHorizontalLabels boolean Show horizontal labels - default: True
fromZero boolean Render charts from 0 not from the minimum value. - default: False
yAxisLabel string Prepend text to horizontal labels -- default: ''
yAxisSuffix string Append text to horizontal labels -- default: ''
xAxisLabel string Prepend text to vertical labels -- default: ''
yAxisInterval string Display y axis line every {x} input. -- default: 1
chartConfig Object Configuration object for the chart, see example config object above
decorator Function This function takes a whole bunch of stuff and can render extra elements, such as data point info or additional markup.
onDataPointClick Function Callback that takes {value, dataset, getColor}
horizontalLabelRotation number (degree) Rotation angle of the horizontal labels - default 0
verticalLabelRotation number (degree) Rotation angle of the vertical labels - default 0
getDotColor function => string Defines the dot color function that is used to calculate colors of dots in a line chart and takes (dataPoint, dataPointIndex)
renderDotContent Function Render additional content for the dot. Takes ({x, y, index, indexData}) as arguments.
yLabelsOffset number Offset for Y axis labels
xLabelsOffset number Offset for X axis labels
hidePointsAtIndex number[] Indices of the data points you don't want to display
formatYLabel Function This function change the format of the display value of the Y label. Takes the Y value as argument and should return the desirable string.
formatXLabel Function This function change the format of the display value of the X label. Takes the X value as argument and should return the desirable string.
getDotProps (value, index) => props This is an alternative to chartConfig's propsForDots
segments number The amount of horizontal lines - default 4

Bezier Line Chart

Line Chart

<LineChart
  data={data}
  width={screenWidth}
  height={256}
  verticalLabelRotation={30}
  chartConfig={chartConfig}
  bezier
/>
Property Type Description
bezier boolean Add this prop to make the line chart smooth and curvy

Progress Ring

Progress Chart

// each value represents a goal ring in Progress chart
const data = {
  labels: ["Swim", "Bike", "Run"], // optional
  data: [0.4, 0.6, 0.8]
};
<ProgressChart
  data={data}
  width={screenWidth}
  height={220}
  strokeWidth={16}
  radius={32}
  chartConfig={chartConfig}
  hideLegend={false}
/>
Property Type Description
data Object Data for the chart - see example above
width Number Width of the chart, use 'Dimensions' library to get the width of your screen for responsive
height Number Height of the chart
strokeWidth Number Width of the stroke of the chart - default: 16
radius Number Inner radius of the chart - default: 32
chartConfig Object Configuration object for the chart, see example config in the beginning of this file
hideLegend Boolean Switch to hide chart legend (defaults to false)

Bar chart

Bat Chart

const data = {
  labels: ["January", "February", "March", "April", "May", "June"],
  datasets: [
    {
      data: [20, 45, 28, 80, 99, 43]
    }
  ]
};
<BarChart
  style={graphStyle}
  data={data}
  width={screenWidth}
  height={220}
  yAxisLabel="$"
  chartConfig={chartConfig}
  verticalLabelRotation={30}
/>
Property Type Description
data Object Data for the chart - see example above
width Number Width of the chart, use 'Dimensions' library to get the width of your screen for responsive
height Number Height of the chart
withVerticalLabels boolean Show vertical labels - default: True
withHorizontalLabels boolean Show horizontal labels - default: True
fromZero boolean Render charts from 0 not from the minimum value. - default: False
withInnerLines boolean Show inner dashed lines - default: True
yAxisLabel string Prepend text to horizontal labels -- default: ''
yAxisSuffix string Append text to horizontal labels -- default: ''
chartConfig Object Configuration object for the chart, see example config in the beginning of this file
horizontalLabelRotation number (degree) Rotation angle of the horizontal labels - default 0
verticalLabelRotation number (degree) Rotation angle of the vertical labels - default 0
showBarTops boolean Show bar tops
showValuesOnTopOfBars boolean Show value above bars

StackedBar chart

StackedBar_Chart

const data = {
  labels: ["Test1", "Test2"],
  legend: ["L1", "L2", "L3"],
  data: [
    [60, 60, 60],
    [30, 30, 60]
  ],
  barColors: ["#dfe4ea", "#ced6e0", "#a4b0be"]
};
<StackedBarChart
  style={graphStyle}
  data={data}
  width={screenWidth}
  height={220}
  chartConfig={chartConfig}
/>
Property Type Description
data Object Data for the chart - see example above
width Number Width of the chart, use 'Dimensions' library to get the width of your screen for responsive
height Number Height of the chart
withVerticalLabels boolean Show vertical labels - default: True
withHorizontalLabels boolean Show horizontal labels - default: True
chartConfig Object Configuration object for the chart, see example config in the beginning of this file
barPercentage Number Defines the percent (0-1) of the available width each bar width in a chart
showLegend boolean Show legend - default: True

Pie chart

Pie Chart

Modified Pie Chart Screenshot

Pie Chart_modified

const data = [
  {
    name: "Seoul",
    population: 21500000,
    color: "rgba(131, 167, 234, 1)",
    legendFontColor: "#7F7F7F",
    legendFontSize: 15
  },
  {
    name: "Toronto",
    population: 2800000,
    color: "#F00",
    legendFontColor: "#7F7F7F",
    legendFontSize: 15
  },
  {
    name: "Beijing",
    population: 527612,
    color: "red",
    legendFontColor: "#7F7F7F",
    legendFontSize: 15
  },
  {
    name: "New York",
    population: 8538000,
    color: "#ffffff",
    legendFontColor: "#7F7F7F",
    legendFontSize: 15
  },
  {
    name: "Moscow",
    population: 11920000,
    color: "rgb(0, 0, 255)",
    legendFontColor: "#7F7F7F",
    legendFontSize: 15
  }
];
<PieChart
  data={data}
  width={screenWidth}
  height={220}
  chartConfig={chartConfig}
  accessor={"population"}
  backgroundColor={"transparent"}
  paddingLeft={"15"}
  center={[10, 50]}
  absolute
/>
Property Type Description
data Object Data for the chart - see example above
width Number Width of the chart, use 'Dimensions' library to get the width of your screen for responsive
height Number Height of the chart
chartConfig Object Configuration object for the chart, see example config in the beginning of this file
accessor string Property in the data object from which the number values are taken
bgColor string background color - if you want to set transparent, input transparent or none.
paddingLeft string left padding of the pie chart
center array offset x and y coordinates to position the chart
absolute boolean shows the values as absolute numbers
hasLegend boolean Defaults to true, set it to false to remove the legend
avoidFalseZero boolean Defaults to false, set it to true to display a "<1%" instead of a rounded value equal to "0%"

Contribution graph (heatmap)

Contribution Graph

This type of graph is often use to display a developer contribution activity. However, there many other use cases this graph is used when you need to visualize a frequency of a certain event over time.

const commitsData = [
  { date: "2017-01-02", count: 1 },
  { date: "2017-01-03", count: 2 },
  { date: "2017-01-04", count: 3 },
  { date: "2017-01-05", count: 4 },
  { date: "2017-01-06", count: 5 },
  { date: "2017-01-30", count: 2 },
  { date: "2017-01-31", count: 3 },
  { date: "2017-03-01", count: 2 },
  { date: "2017-04-02", count: 4 },
  { date: "2017-03-05", count: 2 },
  { date: "2017-02-30", count: 4 }
];
<ContributionGraph
  values={commitsData}
  endDate={new Date("2017-04-01")}
  numDays={105}
  width={screenWidth}
  height={220}
  chartConfig={chartConfig}
/>
Property Type Description
data Object Data for the chart - see example above
width Number Width of the chart, use 'Dimensions' library to get the width of your screen for responsive
height Number Height of the chart
gutterSize Number Size of the gutters between the squares in the chart
squareSize Number Size of the squares in the chart
horizontal boolean Should graph be laid out horizontally? Defaults to true
showMonthLabels boolean Should graph include labels for the months? Defaults to true
showOutOfRangeDays boolean Should graph be filled with squares, including days outside the range? Defaults to false
chartConfig Object Configuration object for the chart, see example config in the beginning of this file
accessor string Property in the data object from which the number values are taken; defaults to count
getMonthLabel function Function which returns the label for each month, taking month index (0 - 11) as argument
onDayPress function Callback invoked when the user clicks a day square on the chart; takes a value-item object

More styling

Every charts also accepts style props, which will be applied to parent svg or View component of each chart.

Abstract Chart

src/abstract-chart.js is an extendable class which can be used to create your own charts!

The following methods are available:

renderHorizontalLines(config)

Renders background horizontal lines like in the Line Chart and Bar Chart. Takes a config object with following properties:

{
  // width of your chart
  width: Number,
  // height of your chart
  height: Number,
  // how many lines to render
  count: Number,
  // top padding from the chart top edge
  paddingTop: Number
}

renderVerticalLabels(config)

Render background vertical lines. Takes a config object with following properties:

{
  // data needed to calculate the number of lines to render
  data: Array,
  // width of your chart
  width: Number,
  // height of your chart
  height: Number,
  paddingTop: Number,
  paddingRight: Number
}

renderDefs(config)

Render definitions of background and shadow gradients

{
  // width of your chart
  width: Number,
  // height of your chart
  height: Number,
  // first color of background gradient
  backgroundGradientFrom: String,
  // first color opacity of background gradient (0 - 1.0)
  backgroundGradientFromOpacity: Number,
  // second color of background gradient
  backgroundGradientTo: String,
  // second color opacity of background gradient (0 - 1.0)
  backgroundGradientToOpacity: Number,
}

Compilation

For production use, the package is automatically compiled after installation, so that you can just install it with npm and use it out-of-the-box.

To transpile TypeScript into JavaScript for development purposes, you can use either run npm run build to compile once, or npm run dev to start compilation in watch mode, which will recompile the files on change.

More information

This library is built on top of the following open-source projects:

Contribute

See the contribution guide and join the contributors!

react-native-chart-kit's People

Contributors

aleksandern avatar artus9033 avatar dchirutac avatar dependabot[bot] avatar devorein avatar foufee avatar geoseong avatar gish94 avatar glibas avatar hermanya avatar ismaelmiber avatar k-yokoishi avatar karszawa avatar m0w93 avatar miwialex avatar msaqlain avatar noktigula avatar olegberman avatar olexandrpadura avatar pixodev avatar pstakoun avatar rapsssito avatar raushanji avatar rishab1065 avatar serayuzgur avatar simonpringlewallace avatar slavkobojanic avatar sreuter avatar stephenc222 avatar wuweijian1997 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

react-native-chart-kit's Issues

undefined is not an object (evaluating 'this.props.style.borderRadius')

I try to make ContributionGraph, and i'm taking this error : TypeError: undefined is not an object (evaluating 'this.props.style.borderRadius')

here is relevant part of my code

`

render() {
const chartConfig = {
  backgroundGradientFrom: '#1E2923',
  backgroundGradientTo: '#08130D',
  color: (opacity = 1) => 'rgba(26, 255, 146, ${opacity})'      
}

const screenWidth = Dimensions.get('window').width
const commitsData = [
  { date: '2017-01-02', count: 1 },
  { date: '2017-01-03', count: 2 },
  { date: '2017-01-04', count: 3 },
  { date: '2017-01-05', count: 4 },
  { date: '2017-01-06', count: 5 },
  { date: '2017-01-30', count: 2 },
  { date: '2017-01-31', count: 3 },
  { date: '2017-03-01', count: 2 },
  { date: '2017-04-02', count: 4 },
  { date: '2017-03-05', count: 2 },
  { date: '2017-02-30', count: 4 }
]

if(this.state.loading){
  return(
  <View style={styles.container}>
    <ActivityIndicator size="large"/>
  </View>
  )
}
return (

  <View style={styles.container}>
    <ContributionGraph
      values={commitsData}
      endDate={new Date('2017-04-01')}
      numDays={105}
      width={screenWidth}
      height={220}
      chartConfig={chartConfig}
    />
  </View>
  
);
}

}`

Don't see vertical labels in BarChart

I created a BarChart according to the sample code. Everything looks good, but I cannot see vertical labels for y-axis. If I switched it to LineChart, vertical labels will show up. Any ideas why?

TypeError: TypeError: TypeError: undefined is not a function (evaluating 'data.entries()[typeof Symbol === "function" ? Symbol.iterator : "@@iterator"]()')

Hi,

I am actually trying to display a pie chart in my react-native project, you can see my code below (exactly the same as the example)

<View style={{ padding: 20, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }}> <PieChart data={[ { name: 'Toronto', population: 2800000 }, { name: 'Dublin', population: 527612 }, { name: 'New York', population: 8538000 }, { name: 'Beijing', population: 21500000 }, { name: 'Moscow', population: 11920000 } ]} width={Dimensions.get('window').width} height={220} chartConfig={{ backgroundGradientFrom: '#ccff33', backgroundGradientTo: '#ffff33', color: () => #000 }} accessor="population" /> </View>

But i'm getting this error:
`TypeError: TypeError: TypeError: undefined is not a function (evaluating 'data.entries()typeof Symbol === "function" ? Symbol.iterator : "@@iterator"')

This error is located at:
in PieChart (at Home.js:17)
in RCTView (at View.js:60)
in View (at Home.js:15)
in RCTView (at View.js:60)
in View (at Home.js:14)
in Home (at SceneView.js:9)
in SceneView (at createTabNavigator.js:10)
in RCTView (at View.js:60)
in View (at createAnimatedComponent.js:154)
in AnimatedComponent (at BottomNavigation.js:558)
in RCTView (at View.js:60)
in View (at createAnimatedComponent.js:154)
in AnimatedComponent (at BottomNavigation.js:543)
in RCTView (at View.js:60)
in View (at BottomNavigation.js:527)
in RCTView (at View.js:60)
in View (at BottomNavigation.js:522)
in BottomNavigation (at withTheme.js:75)
in ThemeProvider (at withTheme.js:89)
in withTheme(BottomNavigation) (at createMaterialBottomTabNavigator.js:25)
in BottomNavigationView (at createTabNavigator.js:115)
in NavigationView (at createNavigator.js:57)
in Navigator (at createNavigationContainer.js:383)
in NavigationContainer (at SceneView.js:9)
in SceneView (at SwitchView.js:12)
in SwitchView (at createNavigator.js:57)
in Navigator (at createNavigationContainer.js:383)
in NavigationContainer (at App.js:34)
in App (at registerRootComponent.js:35)
in RootErrorBoundary (at registerRootComponent.js:34)
in ExpoRootComponent (at renderApplication.js:33)
in RCTView (at View.js:60)
in View (at AppContainer.js:102)
in RCTView (at View.js:60)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:32)

This error is located at:
in NavigationContainer (at SceneView.js:9)
in SceneView (at SwitchView.js:12)
in SwitchView (at createNavigator.js:57)
in Navigator (at createNavigationContainer.js:383)
in NavigationContainer (at App.js:34)
in App (at registerRootComponent.js:35)
in RootErrorBoundary (at registerRootComponent.js:34)
in ExpoRootComponent (at renderApplication.js:33)
in RCTView (at View.js:60)
in View (at AppContainer.js:102)
in RCTView (at View.js:60)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:32)

This error is located at:
in NavigationContainer (at App.js:34)
in App (at registerRootComponent.js:35)
in RootErrorBoundary (at registerRootComponent.js:34)
in ExpoRootComponent (at renderApplication.js:33)
in RCTView (at View.js:60)
in View (at AppContainer.js:102)
in RCTView (at View.js:60)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:32)

  • node_modules\paths-js\pie.js:39:25 in
  • node_modules\react-native-chart-kit\src\pie-chart.js:18:22 in render
  • ... 18 more stack frames from framework internals
    `

I thought that was a problem with a function called data.entries() in the pie_chart.js code but it doesn't exist in it.

May I have some help please ? :)

Bar position when all data is 0

When data = [0, 0, 0, 0, 0, 0, 0]
it shows like this:
screen shot 2018-10-24 at 12 01 28 pm
Is there a way to scale Y-axis as [0,1] so that all the 0 go to the base line?

RNSVGLinearGradient does not exist

Trying to run quick exampe

`export default class Example extends Component {

constructor(props){
super(props);
}

render() {
  const data = {
    labels: ['January', 'February', 'March', 'April', 'May', 'June'],
    datasets: [{
      data: [ 20, 45, 28, 80, 99, 43 ]
    }]
  }


    return (
        <View>
      <LineChart

data={data}
width={200}
height={220}
chartConfig={{
backgroundColor: '#e26a00',
backgroundGradientFrom: '#fb8c00',
backgroundGradientTo: '#ffa726',
color: (opacity = 1) => rgba(255, 255, 255, 1),
style: {
borderRadius: 16
}
}}
/>

);
}
componentDidMount() {

}

}
`

Enviroment-

"react": "16.0.0",
"react-native": "0.51.0",
"react-native-chart-kit": "^1.1.5",

getting error
Invarient Violation : Native component for "RNSVGLinearGradient" does not exist

screen shot 2018-07-23 at 1 38 37 pm

Error while updating property 'd' in shadow node of type: RNSVGPath

I'm using this library
but I got this error message:

Error while updating property 'd' in shadow node of type: RNSVGPath

        <View style={{width:'100%',height:'100%'}}>
            <Text style={{fontSize:20,fontWeight:'bold'}}>
            pichart
            </Text>
            <PieChart
              data={chartAnswered}
              width={chartWidth} // from react-native
              height={220}
              chartConfig={{
                backgroundColor: colorConstants.ONE_APP_COLOR,
                backgroundGradientFrom: colorConstants.ONE_APP_COLOR,
                backgroundGradientTo: '#044675',
                color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
                style: {
                  borderRadius: 16
                }
              }}
              bezier
              style={{
                marginVertical: 8,
                borderRadius: 16
              }}
            />
          </View>

my data:

chartAnswered:[
      { name: 'Italy', population: Math.random() * 10000 },
      { name: 'Mexico', population: Math.random() * 10000 },
      { name: 'France', population: Math.random() * 10000 },
      { name: 'Argentina', population: Math.random() * 10000 },
      { name: 'Japan', population: Math.random() * 10000 }
    ]

my package.json:

  "dependencies": {
    "jalali-moment": "^3.2.1",
    "moment": "^2.22.2",
    "native-base": "^2.6.1",
    "paths-js": "^0.4.7",
    "react": "16.3.1",
    "react-native": "0.55.4",
    "react-native-chart-kit": "^1.1.5",
    "react-native-contacts": "^2.2.2",
    "react-native-document-picker": "^2.1.0",
    "react-native-fs": "^2.11.15",
    "react-native-image-resizer": "^1.0.0",
    "react-native-material-bottom-navigation": "^1.0.0",
    "react-native-progress-bar-animated": "^1.0.6",
    "react-native-slider": "^0.11.0",
    "react-native-svg": "^6.5.2",
    "react-native-vector-icons": "^4.6.0",
    "react-navigation": "^2.8.0",
    "react-redux": "^5.0.7",
    "redux": "^4.0.0",
    "redux-thunk": "^2.3.0",
    "watchman": "^1.0.0"
  },

Crash: removedChildren count (0) was not what we expected (1) in iOS

I am using LineChart with bezier and its working fine in android but showing error
in iOS. App is getting data from firebase then it updates the states. chart renders correctly in android but crashes on ios

`<LineChart

data={{
  labels: this.state.chartLable,
  datasets: [{
    data: this.state.chartData
  }]
}} 
width={wp('96%')} 
height={220}
chartConfig={{
  backgroundColor: '#26d292',
  backgroundGradientFrom: '#22c393',
  backgroundGradientTo: '#22e093',
  decimalPlaces: 2, // optional, defaults to 2dp
  color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
  style: {
    borderRadius: 16,
  }
}}
bezier
style={{
  marginVertical: 8,
  borderRadius: 16,
}}

/>`

screenshot 2018-11-14 at 12 31 08 pm

Add labels to ProgressChart diagram

Love this library, would it be possible to add labels to the ProgressChart diagram? Currently, it shows the value in the label, but it is difficult to let the user know what that value represents i.e. calories, energy, etc

Duplicate module name

After I install the package and start the project, I got several error messages like:

jest-haste-map: @providesModule naming collision:
Duplicate module name: CheckBox
Paths: .../node_modules/react-native-scrollable-tab-view/node_modules/react-native/Libraries/Components/CheckBox/CheckBox.ios.js collides with .../node_modules/react-native-chart-kit/node_modules/react-native/Libraries/Components/CheckBox/CheckBox.ios.js

This warning is caused by a @providesModule declaration with the same name across two different files.
ERROR STARTING PACKAGER

I am using
"expo": "^22.0.0", "npm": "^5.6.0", "prop-types": "^15.6.0", "react": "^16.2.0", "react-native": "^0.49.5",

Objects are not valid as a React child

When I try to import a library, I get an error

Objects are not valid as a React child (found: object with keys {$$typeof, type, key, ref, props, _owner, _store}). If you meant to render a collection of children, use an array instead.

My project looks like this

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Dimensions} from 'react-native';
import {
    LineChart,
    BarChart,
    PieChart,
    ProgressChart,
    ContributionGraph
} from 'react-native-chart-kit'


const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

type Props = {};
export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

Of course I did
yarn add react-native-chart-kit

simulator crash with latest version of Expo

I'm using:

"expo": "^26.0.0",
"react": "16.3.0",
"react-native": "~0.54.1",

and when I test it the iOS simulator crashes, I'm using your example code as source.
can you confirm that it should work, with the above configuration?

Thanks

Can modify color in each Pie at Pie-Chart

Hi.

I just wanted to change each pie's color and set background transparent.

so I modified some codes about things

  1. adjust color on each pie
  2. adjust color on each pie's legend font
  3. alignment - left padding and adjustment of offset x.

I applied pull request so please check this out.

Thanks.

Error while updating property 'd' in shadow node

What's up everyone.

I'm trying to make the chart data dynamic, and the data itself (at the chart) must be updated in accord to an array I've created.

My data is configured as:

data={{labels: labels, datasets: [{ data: net }]}}

Labels are working just fine, but the net array is updated with a new value each 5 seconds. The whole structure seems ok, but I'm always getting this error 'Error while updating property 'd' in shadow node' from react native svg when trying to pass this net array as my dataaset.

Is there any way I can fix it? Just to keep in mind, the chart should update synchronously to the array itself. Thanks guys.

NaN if all data is equal to 0.

In my use case I specifically capture items over the last ten days. If nothing has happened in those ten days the graph will look like this:

img_36453144ebdf-1

As you can see in the bottom left corner it displays NaN when it should display 0.

Here is my data from the server.

labels: [],
datasets: [{
  data: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
}]

Edit:

Also is there any choice for whole numbers only down the Y axis?

Tried to register two views with the same name RNSVGPath

Tried to register two views with the same name RNSVGPath
register
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\react-native\Libraries\Renderer\ReactNativeRenderer-dev.js:14108:4
createReactNativeComponentClass
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\react-native\Libraries\Renderer\ReactNativeRenderer-dev.js:14674:18
default
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\react-native-chart-kit\node_modules\react-native-svg\lib\createReactNativeComponentClass.js:5:38

D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\react-native-chart-kit\node_modules\react-native-svg\elements\Path.js:34:50
loadModuleImplementation
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:214:12
guardedLoadModule
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:148:36
_require
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:132:20

D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\react-native-chart-kit\node_modules\react-native-svg\elements\Rect.js:2
loadModuleImplementation
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:214:12
guardedLoadModule
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:148:36
_require
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:132:20

D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\react-native-chart-kit\node_modules\react-native-svg\index.js:1
loadModuleImplementation
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:214:12
guardedLoadModule
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:148:36
_require
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:132:20

D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\react-native-chart-kit\src\abstract-chart.js:3
loadModuleImplementation
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:214:12
guardedLoadModule
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:148:36
_require
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:132:20

D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\react-native-chart-kit\index.js:1
loadModuleImplementation
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:214:12
guardedLoadModule
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:148:36
_require
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:132:20

D:\Works\Todoc\Desarrollo\Apps\todoc\src\screens\StatisticsScreen.js:5
loadModuleImplementation
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:214:12
guardedLoadModule
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:148:36
_require
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:132:20

D:\Works\Todoc\Desarrollo\Apps\todoc\src\screens\TabsScreen.js:12
loadModuleImplementation
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:214:12
guardedLoadModule
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:148:36
_require
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:132:20

D:\Works\Todoc\Desarrollo\Apps\todoc\App.js:10
loadModuleImplementation
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:214:12
guardedLoadModule
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:148:36
_require
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:132:20

D:\Works\Todoc\Desarrollo\Apps\todoc\index.js:2
loadModuleImplementation
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:214:12
guardedLoadModule
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:141:45
_require
D:\Works\Todoc\Desarrollo\Apps\todoc\node_modules\metro\src\lib\polyfills\require.js:132:20
global code


{
"name": "todoc",
"version": "4.0.0",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"moment": "^2.22.2",
"react": "^16.4.0",
"react-native": "^0.55.4",
"react-native-animatable": "^1.3.0",
"react-native-calendars": "^1.19.3",
"react-native-chart-kit": "^0.2.0",
"react-native-datepicker": "^1.7.2",
"react-native-device-info": "^0.21.5",
"react-native-elements": "^0.19.1",
"react-native-event-listeners": "^1.0.3",
"react-native-floating-action": "^1.10.1",
"react-native-keyboard-aware-scroll-view": "^0.5.0",
"react-native-keyboard-spacer": "^0.4.1",
"react-native-material-bottom-navigation": "^1.0.0",
"react-native-modal": "^6.1.0",
"react-native-modal-selector": "0.0.27",
"react-native-modest-checkbox": "^3.0.0",
"react-native-phone-call": "^1.0.6",
"react-native-popup-menu": "^0.13.1",
"react-native-scrollable-tab-view": "^0.8.0",
"react-native-signalr": "^1.0.6",
"react-native-sms-android": "^0.4.1",
"react-native-svg": "^6.3.1",
"react-native-swiper": "^1.5.13",
"react-native-vector-icons": "^4.6.0",
"react-navigation": "^2.3.0",
"realm": "^2.8.2",
"victory-native": "^0.18.0"
},
"devDependencies": {
"babel-jest": "22.4.3",
"babel-preset-react-native": "4.0.0",
"jest": "22.4.3",
"react-test-renderer": "16.3.0-alpha.1"
},
"jest": {
"preset": "react-native"
}
}

Bezier Style MarginRight Not Working

All, I am trying to center my graph by setting the marginLeft and marginRight to 10. However, marginRight is not working for some reason, marginLeft works but not marginRight. Any suggestions?

<ProgressChart data={data} width={screenWidth} height={150} chartConfig={{ backgroundGradientFrom: '#505050', backgroundGradientTo: '#707070', color: (opacity = 1) =>rgba(255, 255, 255, ${opacity}), style: { borderRadius: 16, } }} bezier style={{ borderRadius: 16, marginRight: 10, marginLeft: 10 }} />
const data = [0.4, 0.6, 0.8]

Unable run demo to contribute

I am unable to get the library demo setup to run on a simulator so I can assist with some cleanup and features.

I installed dependencies, changed main in package.json, and tried running the app :/

Crash when LineChart is re-rendered

The app crashes when LineChart is re-rendered even without any changes to the graph (data, width, height, chartConfig are all same)

iOS crash
removedChildren count (0) was not what we expected (1)
Android crash

Trying to remove a view index above child count 2 view tag: 403
detail: View tag:403
 children(0): [
],
 indicesToRemove(1): [
2,
],
 tagsToDelete(1): [
307,
]

versions:
"react": "16.3.1",
"react-native": "^0.56.0",
"react-native-chart-kit": "^1.1.6",
"react-native-svg": "^7.0.2",

reproducible code

import React from 'react'
import { LineChart } from 'react-native-chart-kit'

const data = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June'],
  datasets: [
    {
      data: [20, 45, 28, 80, 99, 43],
    },
  ],
}

export default class DailyRevenue extends React.Component {
  componentDidMount() {
    setTimeout(() => {
      this.setState({})
    }, 1000)
  }
  render() {
    return (
      <LineChart
        data={data}
        width={400}
        height={400}
        chartConfig={{
          backgroundColor: '#e26a00',
          backgroundGradientFrom: '#fb8c00',
          backgroundGradientTo: '#ffa726',
          color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
          style: {
            borderRadius: 16,
          },
        }}
      />
    )
  }
}

DecimalPlaces property is not used properly

Heya,

Just looked into the code of this awesome charting library and found a bug which could be fixed very easily:

In src/abstract-chart.js we have the renderHorizontalLabels function which gets the decimalPlaces property, but is not used :( It is hardcoded in the code to 2;

<Text
          key={Math.random()}
          x={paddingRight - yLabelsOffset}
          textAnchor="end"
          y={(height * 3 / 4) - ((height - paddingTop) / count * i) + 12}
          fontSize={12}
          fill={this.props.chartConfig.color(0.5)}
        >{count === 1 ? data[0].toFixed(2) : ((this.calcScaler(data) / (count - 1)) * i + Math.min(...data)).toFixed(2)}
        </Text>

To allow us to change the decimalPlaces we need this piece of code: (change 2 to the variable)

<Text
          key={Math.random()}
          x={paddingRight - yLabelsOffset}
          textAnchor="end"
          y={(height * 3 / 4) - ((height - paddingTop) / count * i) + 12}
          fontSize={12}
          fill={this.props.chartConfig.color(0.5)}
        >{count === 1 ? data[0].toFixed(decimalPlaces) : ((this.calcScaler(data) / (count - 1)) * i + Math.min(...data)).toFixed(decimalPlaces)}
        </Text>

@Hermanya I have a PR for this issue: #60

Error while updating property 'strokeWidth' in shadow node of type: RNSVGLine

E/unknown:ReactNative: Exception in native call
com.facebook.react.bridge.JSApplicationIllegalArgumentException: Error while updating property 'strokeWidth' in shadow node of type: RNSVGLine
at com.facebook.react.uimanager.ViewManagersPropertyCache$PropSetter.updateShadowNodeProp(ViewManagersPropertyCache.java:113)
at com.facebook.react.uimanager.ViewManagerPropertyUpdater$FallbackShadowNodeSetter.setProperty(ViewManagerPropertyUpdater.java:154)
at com.facebook.react.uimanager.ViewManagerPropertyUpdater.updateProps(ViewManagerPropertyUpdater.java:58)
at com.facebook.react.uimanager.ReactShadowNodeImpl.updateProperties(ReactShadowNodeImpl.java:378)
at com.facebook.react.uimanager.UIImplementation.createView(UIImplementation.java:289)
at com.facebook.react.uimanager.UIManagerModule.createView(UIManagerModule.java:366)
at java.lang.reflect.Method.invoke(Native Method)
at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:160)
at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)
at android.os.Looper.loop(Looper.java:148)
at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:192)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
at com.facebook.react.bridge.ReadableNativeMap.getString(ReadableNativeMap.java:168)
at com.facebook.react.uimanager.ReactStylesDiffMap.getString(ReactStylesDiffMap.java:71)
at com.facebook.react.uimanager.ViewManagersPropertyCache$StringPropSetter.extractProperty(ViewManagersPropertyCache.java:243)
at com.facebook.react.uimanager.ViewManagersPropertyCache$PropSetter.updateShadowNodeProp(ViewManagersPro

Bar chart data not accurate

If my data is array
labels = ["Today", "Last Day"]
data = [164, 0]

The chart only show "Today" highest number at "123" not "164"

Error rendering LineChart with zero-only data

Hi,
I've encountered a problem trying to render a following chart:

<LineChart
    data={{
        labels: ['January', 'February', 'March', 'April', 'May', 'June'],
        datasets: [{
            data: [0, 0, 0, 0, 0, 0]
        }]
    }}
    width={Dimensions.get('window').width} // from react-native
    height={220}
    chartConfig={{
        backgroundColor: '#2c3e50',
        backgroundGradientFrom: '#2e5a80',
        backgroundGradientTo: '#2e5a85',
        color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
        style: {
            borderRadius: 16
        }
    }}
    style={{
        marginVertical: 8,
    }}
/>

After changing the data array to anything that doesn't have only zeroes (eg. [1,0,0,0,0,0]) in it, the chart renders properly. BarChart renders this exact same attributes fine. The error I'm getting:

Error while updating property 'd' in shadow node of type: RNSVGPath

null

Invalid float: "N"
updateShadowNodeProp
    ViewManagersPropertyCache.java:113
setProperty
    ViewManagerPropertyUpdater.java:154
updateProps
    ViewManagerPropertyUpdater.java:58
updateProperties
    ReactShadowNodeImpl.java:378
createView
    UIImplementation.java:289
createView
    UIManagerModule.java:366
invoke
    Method.java
invoke
    JavaMethodWrapper.java:372
invoke
    JavaModuleWrapper.java:160
run
    NativeRunnable.java
handleCallback
    Handler.java:739
dispatchMessage
    Handler.java:95
dispatchMessage
    MessageQueueThreadHandler.java:29
loop
    Looper.java:148
run
    MessageQueueThreadImpl.java:192
run
    Thread.java:818

Package versions:
react 16.3.1
react-native 0.55.4
react-native-chart-kit 0.1.5
react-native-svg 5.5.1
paths-js 0.4.7

Tested on both emulated && physical Android 7.0

Any help would be appreciated.

I want to love Chart Kit but it has some issues...

First of all, this is my favorite chart library by far. It looks great and the contributions chart is amazing. Unfortunately, I can't really imagine using this in a real setting. In trying to design an app for iOS and Android, I'm finding it really hard to work with. Specifically:

  • The contributions chart refuses to resize
  • The charts that do resize end up looking strange; for example, the Pie Chart does not look good on an iPad because the text size of the labels is too small

All in all, I think the root of the issue is that we don't have enough control over the chart. It feels a bit like putting an image into the app, it looks great but I can't customize it on any meaningful level and sadly that's a deal breaker.

Honestly, I will probably be spending the next few days addressing these issues and hopefully making pull requests, but I thought a discussion couldn't hurt, especially since I could be missing some less obvious features.

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.