mpandroidchart 饼图
时间: 2023-11-02 08:57:35 浏览: 73
要使用 MPAndroidChart 绘制饼图,你需要进行以下步骤:
1.在你的项目中添加 MPAndroidChart 依赖。你可以在 gradle 文件中添加以下代码:
```
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
```
2.在你的布局文件中添加一个 PieChart 视图:
```
<com.github.mikephil.charting.charts.PieChart
android:id="@+id/pie_chart"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
3.在你的 Activity 或 Fragment 中找到这个 PieChart 视图,并为它设置一些属性:
```
PieChart pieChart = findViewById(R.id.pie_chart);
pieChart.setUsePercentValues(true); // 设置使用百分比值
pieChart.getDescription().setEnabled(false); // 隐藏描述
pieChart.setExtraOffsets(5, 10, 5, 5); // 设置间距
pieChart.setDrawHoleEnabled(true); // 绘制中间的空心圆
pieChart.setHoleColor(Color.WHITE); // 设置空心圆的颜色
pieChart.setTransparentCircleRadius(61f); // 设置透明圆的半径
pieChart.setHoleRadius(58f); // 设置空心圆的半径
pieChart.setRotationAngle(0); // 设置起始角度
pieChart.setRotationEnabled(true); // 可以旋转
pieChart.setHighlightPerTapEnabled(true); // 可以高亮显示
```
4.为饼图添加数据。首先创建一个 ArrayList<PieEntry>,然后将每个数据添加到其中:
```
ArrayList<PieEntry> entries = new ArrayList<>();
entries.add(new PieEntry(18.5f, "Green"));
entries.add(new PieEntry(26.7f, "Yellow"));
entries.add(new PieEntry(24.0f, "Red"));
entries.add(new PieEntry(30.8f, "Blue"));
```
5.将数据添加到 PieDataSet 中,并为数据集设置一些属性:
```
PieDataSet dataSet = new PieDataSet(entries, "Election Results");
dataSet.setSliceSpace(3f); // 设置每个扇形之间的间距
dataSet.setSelectionShift(5f); // 设置点击时的扇形半径
dataSet.setColors(ColorTemplate.JOYFUL_COLORS); // 设置颜色
```
6.创建一个 PieData 对象,将数据集传递给它:
```
PieData data = new PieData(dataSet);
data.setValueTextSize(10f); // 设置文字大小
data.setValueTextColor(Color.YELLOW); // 设置文字颜色
```
7.将 PieData 对象设置到 PieChart 中:
```
pieChart.setData(data);
pieChart.invalidate(); // 刷新图表
```
现在,你就可以显示你的饼图了。上面的代码只是一个简单的示例,你可以根据自己的需求调整图表的属性和样式。
相关推荐
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)