MPAndroidChart-向条形图添加标签 [英] MPAndroidChart - Adding labels to bar chart

查看:82
本文介绍了MPAndroidChart-向条形图添加标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的应用程序来说,在条形图的每个条形上都必须有一个标签.有没有办法用MPAndroidChart做到这一点?我在项目wiki/javadocs上找不到执行此操作的方法.

It is necessary for my application to have a label on each bar of the bar chart. Is there a way to do this with MPAndroidChart? I could not find a way to do this on the project wiki/javadocs.

如果没有办法做到这一点,那么还有另一种软件可以让我这么做吗?

If there isn't a way to do this is there another software that will allow me to?

推荐答案

更新后的答案(MPAndroidChart v3.0.1)

作为此类常用功能,该库的v3.0.1添加了

Being such a commonly used feature, v3.0.1 of the library added the IndexAxisValueFormatter class exactly for this purpose, so it's just one line of code now:

mBarChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(labels));

下面原始答案中的 ProTip 仍然适用.

The ProTip from the original answer below still applies.

原始答案(MPAndroidChart v3.0.0)

使用库v3.0.0时,无法直接设置条形标签,但是有一种相当不错的解决方法,可以使用ValueFormatter界面.

With v3.0.0 of the library there is no direct way of setting labels for the bars, but there's a rather decent workaround that uses the ValueFormatter interface.

像这样创建一个新的格式化程序:

Create a new formatter like this:

public class LabelFormatter implements IAxisValueFormatter {
    private final String[] mLabels;

    public LabelFormatter(String[] labels) {
        mLabels = labels;
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        return mLabels[(int) value];
    }
}

然后将此格式化程序设置为您的x轴(假设您已经创建了包含标签的String[]):

Then set this formatter to your x-axis (assuming you've already created a String[] containing the labels):

mBarChart.getXAxis().setValueFormatter(new LabelFormatter(labels));

ProTip::如果要删除放大条形图时出现的多余标签,可以使用粒度功能:

ProTip: if you want to remove the extra labels appearing when zooming into the bar chart, you can use the granularity feature:

XAxis xAxis = mBarChart.getXAxis();
xAxis.setGranularity(1f);
xAxis.setGranularityEnabled(true);

这篇关于MPAndroidChart-向条形图添加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆