MPAndroidChart - 向条形图添加标签

Mat*_*att 13 android mpandroidchart

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

如果没有办法做到这一点是否还有另一个允许我使用的软件?

在此输入图像描述

TR4*_*oid 42

更新的答案(MPAndroidChart v3.0.1)

作为这样一个常用的功能,库的v3.0.1 IndexAxisValueFormatter完全为此目的添加了类,所以它现在只是一行代码:

mBarChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(labels));
Run Code Online (Sandbox Code Playgroud)

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

原始答案(MPAndroidChart v3.0.0)

对于库的v3.0.0,没有直接设置条形标签的方法,但有一个相当不错的解决方法使用该ValueFormatter接口.

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

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

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

mBarChart.getXAxis().setValueFormatter(new LabelFormatter(labels));
Run Code Online (Sandbox Code Playgroud)

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

XAxis xAxis = mBarChart.getXAxis();
xAxis.setGranularity(1f);
xAxis.setGranularityEnabled(true);
Run Code Online (Sandbox Code Playgroud)


小智 7

您可以通过添加此行代码来设置上面的列标签

xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
Run Code Online (Sandbox Code Playgroud)


小智 5

对于实现版本 'com.github.PhilJay:MPAndroidChart:v3.1.0'

您可以使用以下代码段设置标签。

final ArrayList<String> xAxisLabel = new ArrayList<>();
    xAxisLabel.add("Sun");
    xAxisLabel.add("Mon");
    xAxisLabel.add("Tue");
    xAxisLabel.add("Wed");
    xAxisLabel.add("Thu");
    xAxisLabel.add("Fri");
    xAxisLabel.add("Sat");


    XAxis xAxis = chart.getXAxis();
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM_INSIDE);

    ValueFormatter formatter = new ValueFormatter() {


        @Override
        public String getFormattedValue(float value) {
            return xAxisLabel.get((int) value);
        }
    };

    xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
    xAxis.setValueFormatter(formatter);
Run Code Online (Sandbox Code Playgroud)