我现在因工作需要在写一篇中文文章,领导要我用python处理数据和画图,那我也刚好学习一下python画图。
import matplotlib.pyplot as plt
# 饼图数据
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]  # 每个部分的大小
# 绘制饼图
plt.figure(figsize=(6, 6))  # 设置图形大小
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)  # autopct 参数用于显示百分比
plt.axis('equal')  # 使饼图呈现为正圆形
# 添加标题
plt.title('Pie Chart Example')
# 显示图形
plt.show() 

这是最基本的用法。
那我们进阶一下,我们现在要导入我们自己的数据来画图,假设我们的数据在一个xlsx中,那该如何?
import pandas as pd
import matplotlib.pyplot as plt
# 从 Excel 文件中读取数据
excel_file = 'your_excel_file.xlsx'  # 替换为你的 Excel 文件路径
df = pd.read_excel(excel_file)
# 提取数据
labels = df['Category'].tolist()  # 假设 'Category' 列包含标签数据
sizes = df['Value'].tolist()  # 假设 'Value' 列包含每个部分的大小数据
# 绘制饼图
plt.figure(figsize=(6, 6))
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)
plt.axis('equal')
# 添加标题
plt.title('Pie Chart from Excel Data')
# 显示图形
plt.show() 
应用逻辑和R语言差不多,但比R语言复杂多了。