当前位置: 首页> 文旅> 酒店 > Pandas 10-绘制饼图

Pandas 10-绘制饼图

时间:2025/8/23 7:47:54来源:https://blog.csdn.net/qq_52964132/article/details/141787178 浏览次数:0次

1. 准备数据

首先,需要准备一个DataFrame。

import pandas as pd# 创建一个DataFrame
data = {'Category': ['A', 'B', 'C', 'D'],'Value': [15, 30, 45, 10]
}df = pd.DataFrame(data)
print(df)

输出:

  Category  Value
0        A     15
1        B     30
2        C     45
3        D     10

2. 绘制简单饼图

可以使用plot方法来绘制饼图。默认情况下,plot方法会绘制折线图,需要指定kind='pie'来绘制饼图。

import matplotlib.pyplot as plt# 绘制Value列的饼图
df['Value'].plot(kind='pie', labels=df['Category'], autopct='%1.1f%%')
plt.title('Pie Chart of Value by Category')
plt.ylabel('')  # 去掉默认的y轴标签
plt.show()

在这里插入图片描述

3. 自定义饼图

可以通过Matplotlib的API来自定义饼图的样式和标签。

# 自定义饼图
fig, ax = plt.subplots()
ax.pie(df['Value'], labels=df['Category'], autopct='%1.1f%%', startangle=90, colors=['skyblue', 'lightgreen', 'lightcoral', 'lightyellow'])
ax.axis('equal')  # 确保饼图是圆的
plt.title('Customized Pie Chart of Value by Category')
plt.show()

在这里插入图片描述

4. 绘制多列饼图

如果想绘制多列的饼图,可以将DataFrame传递给plot方法,并指定kind='pie'

# 创建一个包含多列数据的DataFrame
data_multi = {'Category': ['A', 'B', 'C', 'D'],'Value1': [15, 30, 45, 10],'Value2': [20, 25, 35, 20]
}df_multi = pd.DataFrame(data_multi)
print(df_multi)# 绘制多列饼图
df_multi.set_index('Category').plot(kind='pie', subplots=True, autopct='%1.1f%%', legend=False)
plt.title('Pie Charts of Multiple Values by Category')
plt.show()

在这里插入图片描述

关键字:Pandas 10-绘制饼图

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: