Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

android - MPAndroidChart - Adding labels to bar chart

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?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Updated Answer (MPAndroidChart 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));

The ProTip from the original answer below still applies.

Original Answer (MPAndroidChart v3.0.0)

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];
    }
}

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...