更新答案(MPAndroidChart v3.0.1)
作为如此常用的功能,该库的 v3.0.1 添加了IndexAxisValueFormatter https://jitpack.io/com/github/PhilJay/MPAndroidChart/v3.0.1/javadoc/com/github/mikephil/charting/formatter/IndexAxisValueFormatter.html正是出于此目的,所以现在只需一行代码:
mBarChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(labels));
The 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];
}
}
然后将此格式化程序设置为您的 x 轴(假设您已经创建了一个String[]
包含标签):
mBarChart.getXAxis().setValueFormatter(new LabelFormatter(labels));
ProTip:如果您想删除放大条形图时出现的额外标签,可以使用粒度功能:
XAxis xAxis = mBarChart.getXAxis();
xAxis.setGranularity(1f);
xAxis.setGranularityEnabled(true);