Hi i have this BarChart that shows the procent of some dadta. How to change the color of the bar if the procent is < 20 in red for example?
This is My Barchart:
<BarChart
//style={graphStyle}
style={{marginBottom: -20}}
data={this.state.chartData}
width={screenWidth - 40}
height={220}
//yAxisLabel="$"
chartConfig={this.state.chartConfig}
verticalLabelRotation={30}
/>
<View style={{padding: 5, paddingTop: 0}}>
{
this.state.labels.map((obj, i) => {
return (
<Text style={{fontSize: 14, marginBottom: 2.5, color: '#666'}}>{i+1}. {obj} ({this.state.chartData.datasets[0].data[i]} gallons({this.state.procent[i]}%))</Text>
)
})
}
</View>
This is chartConfig:
const chartConfig = {
backgroundGradientFrom: "#fff",
//backgroundGradientFromOpacity: 0,
backgroundGradientTo: "#fff",
//backgroundGradientToOpacity: 0.5,
color: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
strokeWidth: 1, // optional, default 3
barPercentage: 0.75,
useShadowColorFromDataset: false // optional
};
Where to add a second color if my procent of data is lover than 20?
This is the picture how it looks.
And if someone knows i am doing a formula to get the procent for the barchart and the Barchart expects data ti fill the vertical row with numbers how can i hardCode it so the number is always 100 at the top of the y?
Since version 6.7.0 you can use the withCustomBarColorFromData prop as introduced with this PR.
This works as follows:
withCustomBarColorFromData prop to truecolors array within your data object. There is bijection between the indices of the colors array and the data indices. You need to provide a function that maps the opacity to a color string.In order to have a custom color if the data point is less then 20, you could manage a separate colors state containing all the necessary functions.
Here is minimal example.
const init = [19, 18, 25, 20, 16];
const MyBarChart = () => {
const [colors, setcolors] = useState(init.map(item => (opacity = 1) => `rgba(0, 0, 0, ${opacity})`))
const [data, setData] = useState(init)
React.useEffect(() => {
setcolors(data.map(item => item < 20 ? (opacity = 1) => `rgba(255, 0, 0, ${opacity})` : (opacity = 1) => `rgba(0, 0, 0, ${opacity})`))
}, [data])
const dataset = {
labels: ["january", "february", "march", "april", "may"],
datasets: [
{
data: data,
colors: colors
}
]
}
return (
<>
<BarChart
data={dataset}
width={300}
height={220}
withCustomBarColorFromData={true}
flatColor={true}
chartConfig={{
backgroundColor: '#ffffff',
backgroundGradientFrom: '#ffffff',
backgroundGradientTo: '#ffffff',
data: dataset.datasets,
color: (opacity = 1) => '#fff',
labelColor: () => '#6a6a6a',
}}
/>
</>
);
};
The result is as follows.