Different Colors for Bars in Barchart Depend on Value

Different colors for bars in BarChart depend on value

In ios-charts, the colors of the bars are set in an array. If your dataset is called barChartDataset, for example, you would set the colors like this

barChartDataset.colors = [UIColor.red,UIColor.orange,UIColor.green,UIColor.black,UIColor.blue]

The bars will have these colors in this order and will repeat. So if you have 10 bars, you would have 2 red bars etc.

In your case, you just have to write a function to return the right color value, and attach it to the array. Reference the code below.

func setColor(value: Double) -> UIColor{

if(value < 30){
return UIColor.red
}
else if(value <= 70 && value >= 30){
return UIColor.orange
}
else if(value > 70){
return UIColor.green
}

else { //In case anything goes wrong
return UIColor.black
}
}

And then wherever you are setting the chart use

 barChartDataset.colors = [setColor(barOneValue),setColor(barTwoValue),setColor(barThreeValue),setColor(barFourValue),setColor(barFiveValue)]

Hope this helps!

Can the colors of bars in a bar chart be varied based on their value?

As far as I know there is no configuration or callback for each individual point being drawn. The best way I can think of to do this would be to create a function that would modify your chart config/data object. This isn't the most elegant way to deal with the problem, but it would work.

The Fix

Pass your chart config/data object to a function that will add the background color.

Main Point of the example is function AddBackgroundColors(chartConfig)

Example:

function AddBackgroundColors(chartConfig) {  var min = 1; // Min value  var max = 100; // Max value  var datasets;  var dataset;  var value;  var range = (max - min);  var percentage;  var backgroundColor;
// Make sure the data exists if (chartConfig && chartConfig.data && chartConfig.data.datasets) { // Loop through all the datasets datasets = chartConfig.data.datasets; for (var i = 0; i < datasets.length; i++) { // Get the values percentage for the value range dataset = datasets[i]; value = dataset.data[0]; percentage = value / range * 100;
// Change the background color for this dataset based on its percentage if (percentage > 100) { // > 100% backgroundColor = '#0000ff'; } else if (percentage >= 50) { // 50% - 100% backgroundColor = '#00ff00'; } else { // < 50% backgroundColor = '#ff0000'; } dataset.backgroundColor = backgroundColor; } }
// Return the chart config object with the new background colors return chartConfig;}
var chartConfig = { type: 'bar', data: { labels: ["percentage"], datasets: [{ label: '100%', data: [100] }, { label: '50%', data: [50] }, { label: '49%', data: [49] }, { label: '5%', data: [5] }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }};
window.onload = function() { var ctx = document.getElementById("canvas").getContext("2d"); chartConfig = AddBackgroundColors(chartConfig); var myChart = new Chart(ctx, chartConfig);};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.2/Chart.bundle.min.js"></script><canvas id="canvas" width="400" height="200"></canvas>

How to custom color Syncfusion BarChart column depending on value in Flutter?

To customize the bar chart for each bar to have a different color there is the need to implement the BarSeries.onCreateRenderer. Take a look at the example below:

Screenshot

Here is a minimal-reproducible-example of this app:

import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return const Scaffold(
body: BarHorizontal(),
);
}
}

/// Renders customized Column chart
class BarHorizontal extends StatefulWidget {
/// Creates customized Column chart
const BarHorizontal({Key? key}) : super(key: key);

@override
State<BarHorizontal> createState() => _BarHorizontalState();
}

class _BarHorizontalState extends State<BarHorizontal> {
_BarHorizontalState();

@override
Widget build(BuildContext context) {
return SfCartesianChart(
title: ChartTitle(text: 'PC vendor shipments - 2015 Q1'),
primaryXAxis: CategoryAxis(
majorGridLines: const MajorGridLines(width: 0),
),
primaryYAxis: NumericAxis(
labelFormat: '{value}M',
title: AxisTitle(text: 'Shipments in million'),
majorGridLines: const MajorGridLines(width: 0),
majorTickLines: const MajorTickLines(size: 0)),
series: <ChartSeries<ChartSampleData, String>>[
BarSeries<ChartSampleData, String>(
onCreateRenderer: (ChartSeries<ChartSampleData, String> series) =>
_CustomColumnSeriesRenderer(),
dataLabelSettings: const DataLabelSettings(
isVisible: true, labelAlignment: ChartDataLabelAlignment.middle),
dataSource: <ChartSampleData>[
ChartSampleData(x: 'HP Inc', y: 12.54),
ChartSampleData(x: 'Lenovo', y: 13.46),
ChartSampleData(x: 'Dell', y: 9.18),
ChartSampleData(x: 'Apple', y: 4.56),
ChartSampleData(x: 'Asus', y: 5.29),
],
width: 0.8,
xValueMapper: (ChartSampleData sales, _) => sales.x as String,
yValueMapper: (ChartSampleData sales, _) => sales.y,
)
],
);
}
}

class _CustomColumnSeriesRenderer extends BarSeriesRenderer {
_CustomColumnSeriesRenderer();

@override
BarSegment createSegment() {
return _ColumnCustomPainter();
}
}

class _ColumnCustomPainter extends BarSegment {
final colorList = [
const Color.fromRGBO(53, 92, 125, 1),
const Color.fromRGBO(192, 108, 132, 1),
const Color.fromRGBO(246, 114, 128, 1),
const Color.fromRGBO(248, 177, 149, 1),
const Color.fromRGBO(116, 180, 155, 1)
];

@override
Paint getFillPaint() {
final Paint customerFillPaint = Paint();
customerFillPaint.isAntiAlias = false;
customerFillPaint.color = colorList[currentSegmentIndex!];
customerFillPaint.style = PaintingStyle.fill;
return customerFillPaint;
}
}

class ChartSampleData {
ChartSampleData({this.x, this.y});

final dynamic x;
final num? y;
}

Different color for each bar in a bar chart; ChartJS

After looking into the Chart.Bar.js file I've managed to find the solution.
I've used this function to generate a random color:

function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}

I've added it to the end of the file and i called this function right inside the "fillColor:" under

helpers.each(dataset.data,function(dataPoint,index){
//Add a new point for each piece of data, passing any required data to draw.

so now it looks like this:

helpers.each(dataset.data,function(dataPoint,index){
//Add a new point for each piece of data, passing any required data to draw.

datasetObject.bars.push(new this.BarClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
strokeColor : dataset.strokeColor,
fillColor : getRandomColor(),
highlightFill : dataset.highlightFill || dataset.fillColor,
highlightStroke : dataset.highlightStroke || dataset.strokeColor
}));
},this);

and it works I get different color for each bar.

Plotting different colors on bar chart values If the number falls below 0

plt.bar accepts a parameter color= which either can be a single color, or a list with one color for each of the bars. The list can be constructed via list comprehension, giving a color depending on a constraint.

A bar plot normally only generates one entry in the legend (via plt.bar(..., label='my barplot'). To get more than one label, and also to have it circular instead of rectangular, custom legend elements can be created.

Here is some example code to get you started:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib

df = pd.DataFrame({'Years': ['2015', '2016', '2017', '2018'],
'Value': [-495982.0, 405549.0, -351541.0, 283790.0]})
values = df["Value"]
values = values / 1e3
asOfDates = df['Years']

Value = df['Value'] / 100

fig, ax = plt.subplots()
ax.set_title('Plotting Financials')
ax.set_xlabel('Years')
ax.set_ylabel('value')
plt.bar(asOfDates, values, color=['r' if v < 0 else 'g' for v in values])
ax.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))

legend_handles = [Line2D([0], [0], linewidth=0, marker='o', markerfacecolor=color, markersize=12, markeredgecolor='none')
for color in ['g', 'r']]
ax.legend(legend_handles, ['positive', 'negative'])

plt.show()

example plot



Related Topics



Leave a reply



Submit