Ziv Kesten Ziv Kesten - 6 months ago 58
Android Question

MPAndroidChart is there a way to set different colors for different bars?

I am using MPAndroidChart in my app and i was wondering if there is a way to set a diferent color for the first bar in a dynamically moving bar chart, like this:
enter image description here

The bars are added dynamically while the whole stack is being moved to the left as the data keeps coming, is there a way to set the color of the first bar to be a different color?
thank you in advance.

EDIT and Solution:
here is my code for adding a new entry to the chart, it occurs dynamically every 500 millis or so.

private void addBarEntry(float value) {

BarData data = mDownloadChart.getData();

if(data != null) {

BarDataSet set = data.getDataSetByIndex(0);
// set.addEntry(...); // can be called as well

if (set == null) {
set = createBarSet();

// add a new x-value first
data.addXValue(set.getEntryCount() + "");

// choose a random dataSet
//int randomDataSetIndex = (int) (Math.random() * data.getDataSetCount());

data.addEntry(new BarEntry(value, set.getEntryCount()), 0);

// let the chart know it's data has changed

SLog.d(TAG, "download value: "+value);


// redraw the chart

Thanks to @Philipp Jahoda I got it to work, just add this piece of code in you addEntry method:

int[] colors = new int[set.getEntryCount()];
for (int i = 0; i<colors.length; i++){
colors[colors.length-1] = Color.parseColor("your-hex-color-for-last-entry");


Answer Source

Yes, there is, it's in the documentation.

Basically you can set a separate color for each bar in the chart. It's a little inconvenient at the moment because in your case you have to set each color to "red" and the last color to "green".

I'm working on improving that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download