首页 文章

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

提问于
浏览
1

enter image description here
我正在使用MPAndroid库 . 实现'com.github.PhilJay:MPAndroidChart:v3.0.3'我需要创建带标签的BarChart . 我的代码如下,但它不起作用:这是要显示的数组 .

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

如果make代码没有标签就行了 .

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

我必须使用一系列标签 . 提前致谢 .

我需要像这样创建图形 . 请帮我 .

2 回答

  • 3

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

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

    附:你不需要 getBarEntryLabels 方法 .

    结果如下:

    enter image description here

  • 1

    您需要执行以下操作:

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

    快乐编码:)

相关问题