Search code examples
javaandroidxmlpie-chartmpandroidchart

How to center the legend in pie chart drawn using MPAndroidChart library?


What I have done: I have created a pie chart using MPAndroidChart library and ended up having the legend in the left corner. I tried changing the pie chart width but then when the items increase legend tends to wrap to a second line.

What I expect: I want the legend to be in the center every time when it updates. Even legend wrap to the second line, I want it to be in the center. I would appreciate any suggestions on this.

Thank you!

enter image description here

<com.github.mikephil.charting.charts.PieChart
        android:id="@+id/chart"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_gravity="center_horizontal"
        >

    </com.github.mikephil.charting.charts.PieChart>

Activity Code :

private void setupPieChart(){

    //pupulating list of PieEntires
    List<PieEntry> pieEntires = new ArrayList<>();
    for( int i = 0 ; i<time.length;i++){
        pieEntires.add(new PieEntry(time[i],activity[i]));
    }
    PieDataSet dataSet = new PieDataSet(pieEntires,"");
    dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
    PieData data = new PieData(dataSet);
    //pie slices text value
    data.setValueTextSize(10);
    //Get the chart
    pieChart.setData(data);
    pieChart.invalidate();
    pieChart.setCenterText("50%");
    pieChart.setDrawEntryLabels(false);
    pieChart.setContentDescription("");
    //pieChart.setDrawMarkers(true);
    //pieChart.setMaxHighlightDistance(34);
    pieChart.setEntryLabelTextSize(12);
    pieChart.setHoleRadius(75);
    //to remove bottom left description
    pieChart.getDescription().setEnabled(false);

    //legend attributes
    Legend legend = pieChart.getLegend();
    legend.setForm(Legend.LegendForm.CIRCLE);
    legend.setTextSize(12);
    legend.setFormSize(20);
    legend.setFormToTextSpace(2);
    //to wrap legend text
    legend.setWordWrapEnabled(true);
    Log.d("legend " ,legend.getEntries().toString());
}

Solution

  • I was able to center the legend by adding the below line in setupPieChart() mentioned in the question above.

    legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);