使用 MPAndroid 库在条形图中设置标签不起作用

Set Label is not working in Bar Chart using MPAndroid Library

我正在使用 MPAndroid 库。 实施 'com.github.PhilJay:MPAndroidChart:v3.0.3' 我需要创建带有标签的条形图。 我的代码如下,但它不起作用: 这是要显示的柱形数组。

public ArrayList<BarEntry> getBarEntryArrayList() {

    ArrayList<BarEntry> barEntries = new ArrayList<BarEntry>();
    barEntries.add(new BarEntry(2f, 0));
    barEntries.add(new BarEntry(4f, 1));
    barEntries.add(new BarEntry(6f, 2));
    barEntries.add(new BarEntry(8f, 3));
    barEntries.add(new BarEntry(7f, 4));
    barEntries.add(new BarEntry(3f, 5));
    return barEntries;

}

这是要显示在底部的标签数组。

public ArrayList<String> getBarEntryLabels() {

    ArrayList<String> BarEntryLabels = new ArrayList<String>();
    BarEntryLabels.add("J");
    BarEntryLabels.add("F");
    BarEntryLabels.add("M");
    BarEntryLabels.add("A");
    BarEntryLabels.add("M");
    BarEntryLabels.add("J");
    BarEntryLabels.add("J");
    BarEntryLabels.add("A");
    BarEntryLabels.add("S");
    BarEntryLabels.add("O");
    BarEntryLabels.add("N");
    BarEntryLabels.add("D");
    return BarEntryLabels;

}

设置标签数组和条目数组时出现问题

private void setBarChartData() {
    BarDataSet barDataSet = new BarDataSet(getBarEntryArrayList(), getBarEntryLabels() );
    barDataSet.setColors(ColorTemplate.COLORFUL_COLORS);
    BarData barData = new BarData(barDataSet);
    barChart.setData(barData);
    barChart.animateY(3000);

}

这条线不工作。

BarDataSet barDataSet = new BarDataSet(getBarEntryArrayList(), getBarEntryLabels() );

如果生成没有标签的代码,它就可以工作。

BarDataSet barDataSet = new BarDataSet(getBarEntryArrayList(), "Dummy text" );

我必须使用标签数组。 提前致谢。

我需要创建这样的图表。 请帮助我。

创建栏条目时,将标签添加为第三个参数:

    barEntries.add(new BarEntry(2f, 0, "J"));
    barEntries.add(new BarEntry(4f, 1, "F"));
    barEntries.add(new BarEntry(6f, 2, "M"));
    barEntries.add(new BarEntry(8f, 3, "A"));
    barEntries.add(new BarEntry(7f, 4, "M"));
    barEntries.add(new BarEntry(3f, 5, "P"));

barChart.setData(barData); 之后,您可以使用 setValueFormatter:

将标签设置为高于或低于柱线
    barChart.getBarData().setValueFormatter(new IValueFormatter() {
        @Override
        public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
            return entry.getData().toString();
        }
    });

同时增加字体大小:

barChart.getData().setValueTextSize(15);

P.S。你不需要 getBarEntryLabels 方法。

结果如下:

您需要执行以下操作:

barChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(BarEntryLabels));

快乐编码:)

您可以通过以下方式设置,

在 Kotlin 中,

val xAxis = chart.xAxis
xAxis.valueFormatter = IndexAxisValueFormatter(labels)

如果您仍然遇到问题,请确保您没有隐藏 x 轴。如果隐藏 x 轴,则不会显示标签。如果你想隐藏 x-Axis,你必须让 x-Axis 可见并给它一个透明的颜色。