如何使用MPAndroidChart设置x轴标签

kem*_*emp 11 android mpandroidchart

我在我的应用程序中使用MPAndroidChart,如下所示:

在此输入图像描述

但我无法添加这样的标签

Pra*_*abs 25

你需要你的标签而不是那些价值吗?

如果是这样,那么它就是这样做的方法.

XAxis标签添加到ArrayList

    final ArrayList<String> xLabel = new ArrayList<>();
    xLabel.add("9");
    xLabel.add("15");
    xLabel.add("21");
    xLabel.add("27");
    xLabel.add("33");  

    // or use some other logic to save your data in list. For ex. 
    for(i=1; i<50; i+=2)
    { 
       xLabel.add(""+3*i);
    }
Run Code Online (Sandbox Code Playgroud)

然后在中使用此标签setValueFormatter.
例如:

    XAxis xAxis = mChart.getXAxis();
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setDrawGridLines(false);
    xAxis.setValueFormatter(new IAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            return xLabel.get((int)value);
        }
    });
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

  • `value` 不是条目的位置,你不是把它当作一个位置吗? (2认同)

Mah*_*raa 5

您可以覆盖 AxisValueFormatter

IE:

xAxis.setValueFormatter(new AxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return "YOUR_TEXT"; // here you can map your values or pass it as empty string
            }

            @Override
            public int getDecimalDigits() {
                return 0; //show only integer
            }
        });
Run Code Online (Sandbox Code Playgroud)

您可以选择组的中心值来映射组名称,其他为空。那将是最简单的方法。

  • 谢谢你的回答。但是当我使用 getFormattedValue(float value, AxisBase axis) 时,返回值总是 0,4,8,12,16,20 ,而我的中心值是 3,9,15,21。我会使我的标签位置错误 (2认同)