mpAndroidChart 堆叠图实现
时间: 2024-06-09 09:04:31 浏览: 8
mpAndroidChart 是一个强大的开源图表库,支持多种类型的图表,包括折线图、柱状图、饼图、散点图、雷达图等。在 mpAndroidChart 中,堆叠图可以通过设置数据集的方式来实现。下面是一个简单的堆叠图实现示例:
1. 引入库
在项目的 build.gradle 文件中添加以下依赖:
```
dependencies {
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}
```
2. 布局文件中添加 ChartView
在布局文件中添加 ChartView 控件:
```
<com.github.mikephil.charting.charts.BarChart
android:id="@+id/bar_chart"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
3. 初始化 ChartView
在代码中获取 ChartView 控件,并进行初始化:
```
BarChart barChart = findViewById(R.id.bar_chart);
// 禁用描述
barChart.getDescription().setEnabled(false);
// 禁用缩放
barChart.setPinchZoom(false);
barChart.setScaleEnabled(false);
// 设置 X 轴
XAxis xAxis = barChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setGranularity(1f);
xAxis.setLabelCount(dataList.size());
// 设置 Y 轴
YAxis leftAxis = barChart.getAxisLeft();
leftAxis.setAxisMinimum(0f);
leftAxis.setDrawGridLines(false);
YAxis rightAxis = barChart.getAxisRight();
rightAxis.setAxisMinimum(0f);
rightAxis.setDrawGridLines(false);
```
4. 设置数据
在代码中设置数据集:
```
// 创建数据集
List<BarEntry> entries1 = new ArrayList<>();
List<BarEntry> entries2 = new ArrayList<>();
// 添加数据
for (int i = 0; i < dataList.size(); i++) {
entries1.add(new BarEntry(i, dataList.get(i).getValue1()));
entries2.add(new BarEntry(i, dataList.get(i).getValue2()));
}
// 创建 BarDataSet 对象
BarDataSet dataSet1 = new BarDataSet(entries1, "数据集1");
dataSet1.setColor(Color.parseColor("#FFC107"));
dataSet1.setValueTextColor(Color.parseColor("#333333"));
BarDataSet dataSet2 = new BarDataSet(entries2, "数据集2");
dataSet2.setColor(Color.parseColor("#2196F3"));
dataSet2.setValueTextColor(Color.parseColor("#333333"));
// 设置数据
BarData barData = new BarData(dataSet1, dataSet2);
barData.setBarWidth(0.3f);
barChart.setData(barData);
// 刷新图表
barChart.invalidate();
```
5. 效果展示
最终效果如下图所示:
![堆叠图](https://img-blog.csdnimg.cn/20211203154313785.png)
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)