要为MPAndroidChart的BarChart添加图例(说明使用的颜色),可以按照以下步骤进行操作:
setColors()
方法设置颜色数组,每个颜色对应一个柱状图。BarDataSet dataSet = new BarDataSet(entries, "Label");
dataSet.setColors(new int[]{Color.RED, Color.GREEN, Color.BLUE});
setCustom()
方法设置自定义的Legend样式。Legend legend = chart.getLegend();
legend.setCustom(new int[]{Color.RED, Color.GREEN, Color.BLUE}, new String[]{"Label 1", "Label 2", "Label 3"});
BarData barData = new BarData(dataSet);
chart.setData(barData);
完整的代码示例:
BarChart chart = findViewById(R.id.chart);
ArrayList<BarEntry> entries = new ArrayList<>();
entries.add(new BarEntry(0, 10));
entries.add(new BarEntry(1, 20));
entries.add(new BarEntry(2, 30));
BarDataSet dataSet = new BarDataSet(entries, "Label");
dataSet.setColors(new int[]{Color.RED, Color.GREEN, Color.BLUE});
Legend legend = chart.getLegend();
legend.setCustom(new int[]{Color.RED, Color.GREEN, Color.BLUE}, new String[]{"Label 1", "Label 2", "Label 3"});
BarData barData = new BarData(dataSet);
chart.setData(barData);
chart.invalidate();
这样,就为BarChart添加了图例,图例中显示了使用的颜色及其对应的标签。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云