Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MPAndroidChart - all pieces of the pie chart are the same colour

I am using MPAndroidChart (https://github.com/PhilJay/MPAndroidChart) library to generate pie chart. I followed multiple tutorials including the wiki page, but when I create my pie chart all of the pieces are the same color. Any idea how can I solve this ?

Code:

PieChart mChart = (PieChart) findViewById(R.id.piechart);

List<PieEntry> pieChartEntries = new ArrayList<>();

pieChartEntries.add(new PieEntry(18.5f, "Green"));
pieChartEntries.add(new PieEntry(26.7f, "Yellow"));
pieChartEntries.add(new PieEntry(24.0f, "Red"));
pieChartEntries.add(new PieEntry(30.8f, "Blue"));

PieDataSet set = new PieDataSet(pieChartEntries, "Emotion Results");
PieData data = new PieData(set);
mChart.setData(data);
set.setColors(R.color.pieColour1,R.color.pieColour2,R.color.pieColour3,R.color.pieColour4,R.color.pieColour5,R.color.pieColour6,R.color.pieColour7,R.color.pieColour8);
mChart.invalidate();

enter image description here

like image 625
Matt D. Avatar asked Mar 18 '18 13:03

Matt D.


1 Answers

The documentation says:

When adding some additional styling, the resulting PieChart with the data used above could look similar to this

These are not the real colors, but oly the labels for the colors:

pieChartEntries.add(new PieEntry(18.5f, "Green"));
pieChartEntries.add(new PieEntry(26.7f, "Yellow"));
pieChartEntries.add(new PieEntry(24.0f, "Red"));
pieChartEntries.add(new PieEntry(30.8f, "Blue"));

To add colors to the PieChart you use:

set.setColors(new int[]{Color.parseColor("#FF32DA64"),
                    Color.parseColor("#FF32DAD4"),
                    Color.parseColor("#FFB853F2"),
                    Color.parseColor("#FFF2ED53")});

or you can use one of the templates:

set.setColors(ColorTemplate.COLORFUL_COLORS);

EDIT:

I just saw you're using the colors from the resources, if you inspect the setColors method you should see this:

If you are using colors from the resources,make sure that the colors are already prepared (by calling getResources().getColor(...))

So in your case you need to resolve the resources into Color objects before adding them to the set.

like image 93
Levi Moreira Avatar answered Nov 20 '22 04:11

Levi Moreira