I am trying to customize legend but not able to do so.My purpose is to give different legend labels.I ma using MPChart library to do so.
ArrayList<BarEntry> entries = new ArrayList<>();
entries.add(new BarEntry(4f, 0));
entries.add(new BarEntry(8f, 1));
entries.add(new BarEntry(6f, 2));
entries.add(new BarEntry(12f, 3));
entries.add(new BarEntry(18f, 4));
mColors.add(R.color.red);
mColors.add(R.color.text_color_gray);
mColors.add(R.color.text_color_blue);
mColors.add(R.color.green);
mColors.add(R.color.black);
BarDataSet dataset = new BarDataSet(entries, null);
ArrayList<String> labels = new ArrayList<String>();
labels.add("05");
labels.add("06");
labels.add("07");
labels.add("08");
labels.add("09");
BarData data = new BarData(labels, dataset);
Legend legend = mChart.getLegend();
legend.setEnabled(true);
legend.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
legend.setForm(Legend.LegendForm.SQUARE);
legend.setColors(mColors);
legend.setLabels(mLabels);
mChart.setData(data);
mChart.animateY(2000);
LimitLine line = new LimitLine(10f);
YAxis yAxis = mChart.getAxisLeft();
yAxis.addLimitLine(line);
yAxis.setDrawAxisLine(true);
mChart.setDrawValueAboveBar(true);
mChart.setDrawBarShadow(false);
mChart.setVisibleXRange(4);
mChart.moveViewToX(2);
mChart.setDrawValueAboveBar(false);
mChart.invalidate();
Please let me know any solution for this.
By default, all chart types support legends and will automatically generate and draw a legend after setting data for the chart. The Legend usually consists of multiple entries each represented by a label an a form/shape.
Legend is a broad label used for a group of objects. Label is used for labeling specific elements.
you can custom your legend like this
LegendEntry legendEntryA = new LegendEntry();
legendEntryA.label = "a";
legendEntryA.formColor = Color.GREEN;
And add them to legend of the chart
legend.setCustom(Arrays.asList(legendEntryA, legendEntryB, legendEntryC, legendEntryD));
If you want to have 4 legend labels, you need 4 BarDataSet objects.
Having different colours will only group the different colours on the one legend that will be generated.
And you need to pass the colors to the DataSet and it will be mapped with the Legend.
Finally, your DataSets need a label which will be used for the legend. You can specify the label as second parameter in the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With