How to set legend labels MPChart

被刻印的时光 ゝ 提交于 2021-02-19 02:46:25

问题


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.


回答1:


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, you DataSets need a label which will be used for the legend. You can specify the label as second parameter in the constructor.




回答2:


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));


来源:https://stackoverflow.com/questions/30185570/how-to-set-legend-labels-mpchart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!