我尝试过的大多数答案都存在问题,比如标签错位、不居中或条形图被隐藏在屏幕空间之外。经过一番尝试后,我终于有一个正常工作的 poc。
最后4行是最重要的。
ArrayList<BarEntry> barEntries = new ArrayList<>();
ArrayList<BarEntry> barEntries1 = new ArrayList<>();
ArrayList<BarEntry> barEntries2 = new ArrayList<>();
ArrayList<BarEntry> barEntries3 = new ArrayList<>();
barEntries.add(new BarEntry(1,989.21f));
barEntries.add(new BarEntry(2,420.22f));
barEntries.add(new BarEntry(3,758));
barEntries.add(new BarEntry(4,3078.97f));
barEntries.add(new BarEntry(5,14586.96f));
barEntries.add(new BarEntry(6,400.4f));
barEntries.add(new BarEntry(7,5888.58f));
barEntries1.add(new BarEntry(1,950));
barEntries1.add(new BarEntry(2,791));
barEntries1.add(new BarEntry(3,630));
barEntries1.add(new BarEntry(4,782));
barEntries1.add(new BarEntry(5,2714.54f));
barEntries1.add(new BarEntry(6,500));
barEntries1.add(new BarEntry(7,2173.36f));
barEntries2.add(new BarEntry(1,900));
barEntries2.add(new BarEntry(2,691));
barEntries2.add(new BarEntry(3,1030));
barEntries2.add(new BarEntry(4,382));
barEntries2.add(new BarEntry(5,2714f));
barEntries2.add(new BarEntry(6,5000));
barEntries2.add(new BarEntry(7,1173f));
barEntries3.add(new BarEntry(1,200));
barEntries3.add(new BarEntry(2,991));
barEntries3.add(new BarEntry(3,1830));
barEntries3.add(new BarEntry(4,3082));
barEntries3.add(new BarEntry(5,214));
barEntries3.add(new BarEntry(6,5600));
barEntries3.add(new BarEntry(7,9173));
BarDataSet barDataSet = new BarDataSet(barEntries,"DATA SET 1");
barDataSet.setColor(Color.parseColor("#F44336"));
BarDataSet barDataSet1 = new BarDataSet(barEntries1,"DATA SET 2");
barDataSet1.setColors(Color.parseColor("#9C27B0"));
BarDataSet barDataSet2 = new BarDataSet(barEntries2,"DATA SET 3");
barDataSet1.setColors(Color.parseColor("#e241f4"));
BarDataSet barDataSet3 = new BarDataSet(barEntries3,"DATA SET 4");
barDataSet1.setColors(Color.parseColor("#42f46e"));
String[] months = new String[] {"TYPE 1", "TYPE 2", "TYPE 3", "TYPE 4"};
BarData data = new BarData(barDataSet,barDataSet1,barDataSet2,barDataSet3);
barChart.setData(data);
XAxis xAxis = barChart.getXAxis();
xAxis.setValueFormatter(new IndexAxisValueFormatter(months));
barChart.getAxisLeft().setAxisMinimum(0);
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setGranularity(1);
xAxis.setCenterAxisLabels(true);
xAxis.setGranularityEnabled(true);
float barSpace = 0.02f;
float groupSpace = 0.3f;
int groupCount = 4;
data.setBarWidth(0.15f);
barChart.getXAxis().setAxisMinimum(0);
barChart.getXAxis().setAxisMaximum(0 + barChart.getBarData().getGroupWidth(groupSpace, barSpace) * groupCount);
barChart.groupBars(0, groupSpace, barSpace);
我得到的最终结果是:
![固定标签的条形图](https://istack.dev59.com/82L6M.webp)