Open dahudson88 opened 5 years ago
Also is there a way to remove the percentages from the legend?
Not right now, but I would welcome a PR
Also is there a way to make the legend horizontally instead of Vertical?
Also is there a way to make the legend horizontally instead of Vertical?
Up
Also is there a way to make the legend horizontally instead of Vertical?
I had to do it on my own.
CustomPieChart
import React, { useMemo } from "react";
import { View, Text, StyleSheet, Dimensions } from "react-native";
import { FontAwesome } from "@expo/vector-icons";
import { PieChart } from "react-native-chart-kit";
const CustomPieChart = ({ data, accessor, absolute }) => {
// Order by asscesor value
const sortedData = useMemo(() => {
return data.sort((a, b) => b[accessor] - a[accessor]);
}, data);
const percentages = useMemo(() => {
// Get the total value of all dataitems
const grandTotal = data.reduce((acum, item) => acum + item[accessor], 0);
return data.reduce((acum, item) => {
const percentageOfDataItem = (item[accessor] * 100) / grandTotal;
return {
...acum,
[item.name]: percentageOfDataItem.toFixed(2),
};
}, {});
}, [absolute, data, accessor]);
return (
<View style={styles}>
<PieChart
data={data}
width={Dimensions.get("window").width}
height={220}
chartConfig={{
backgroundColor: "#ffffff",
backgroundGradientFrom: "white",
backgroundGradientTo: "white",
decimalPlaces: 2, // optional, defaults to 2dp
color: (opacity = 1) => `rgba(54,64,81, ${opacity})`,
}}
accessor={accessor}
backgroundColor="transparent"
hasLegend={false}
paddingLeft={Dimensions.get("window").width / 4}
/>
<View style={styles.legend}>
{sortedData.map((dataItem) => (
<View style={styles.legendItem} key={dataItem.name}>
<FontAwesome name="circle" size={24} color={dataItem.color} />
<Text style={styles.legendItemValue}>
{absolute
? dataItem[accessor]
: `${percentages[dataItem.name]}%`}
</Text>
<Text>{dataItem.name}</Text>
</View>
))}
</View>
</View>
);
};
const styles = StyleSheet.create({
legend: {
marginHorizontal: 10,
},
legendItem: {
flexDirection: "row",
},
legendItemValue: {
marginHorizontal: 10,
},
});
export default CustomPieChart;
Usage
import React from 'react'
import {View} from 'react-native'
import CustomPieChart from "../components/CustomPieChart";
const MyView = () => {
const chartData = [{
name: 'Food',
total: 10000,
color: '#ff3333',
legendFontColor: "#7F7F7F",
legendFontSize: 15,
},{
name: 'Bills',
total: 50000,
color: '#ffff34',
legendFontColor: "#7F7F7F",
legendFontSize: 15,
},{
name: 'Housing',
total: 90000,
color: '#31ff34',
legendFontColor: "#7F7F7F",
legendFontSize: 15,
}]
return (
<View>
<CustomPieChart data={chartData} accessor="total" absolute={false} />
</View>
)
}
export default MyView
Result
@Jucesr I got this error: Warning: The final argument passed to useMemo changed size between renders. The order and size of this array must remain constant.
can u help?
Is it possible currently to add labels to the pie chart that shows a the value of the slice?