android studio 多列柱状图
时间: 2023-12-07 19:39:08 浏览: 223
以下是使用MPAndroidChart库在Android Studio中实现多列柱状图的示例代码:
1. 首先,在app的build.gradle文件中添加依赖项:
```gradle
dependencies {
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}
```
2. 在布局文件中添加CombinedChart视图:
```xml
<com.github.mikephil.charting.charts.CombinedChart
android:id="@+id/chart"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
3. 在Java代码中设置数据和样式:
```java
// 获取CombinedChart视图
CombinedChart chart = findViewById(R.id.chart);
// 创建数据集
CombinedData data = new CombinedData();
// 添加柱状图数据
BarData barData = new BarData();
List<BarEntry> entries1 = new ArrayList<>();
entries1.add(new BarEntry(0, new float[]{10f, 20f, 30f}));
entries1.add(new BarEntry(1, new float[]{20f, 30f, 40f}));
entries1.add(new BarEntry(2, new float[]{30f, 40f, 50f}));
barData.addDataSet(new BarDataSet(entries1, "数据1"));
List<BarEntry> entries2 = new ArrayList<>();
entries2.add(new BarEntry(0, new float[]{20f, 30f, 40f}));
entries2.add(new BarEntry(1, new float[]{30f, 40f, 50f}));
entries2.add(new BarEntry(2, new float[]{40f, 50f, 60f}));
barData.addDataSet(new BarDataSet(entries2, "数据2"));
// 添加折线图数据
LineData lineData = new LineData();
List<Entry> entries3 = new ArrayList<>();
entries3.add(new Entry(0, 10f));
entries3.add(new Entry(1, 20f));
entries3.add(new Entry(2, 30f));
lineData.addDataSet(new LineDataSet(entries3, "数据3"));
// 将数据集添加到CombinedData中
data.setData(barData);
data.setData(lineData);
// 设置样式
chart.setData(data);
chart.getDescription().setEnabled(false);
chart.setDrawGridBackground(false);
chart.setDrawBarShadow(false);
chart.setHighlightFullBarEnabled(false);
chart.setDrawOrder(new CombinedChart.DrawOrder[]{
CombinedChart.DrawOrder.BAR, CombinedChart.DrawOrder.LINE
});
chart.getAxisRight().setEnabled(false);
chart.getAxisLeft().setAxisMinimum(0f);
chart.getXAxis().setAxisMinimum(0f);
chart.getXAxis().setGranularity(1f);
chart.getXAxis().setCenterAxisLabels(true);
chart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(new String[]{"列1", "列2", "列3"}));
chart.animateY(1000);
```
4. 运行程序即可看到多列柱状图。
阅读全文