import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = ["simhei"]
# 绘制圆环图,并返回饼块对象
data=pd.read_excel(r'C:\Users\Administrator\Desktop\数据帮\数据处理\数据源\负面信息.xlsx')
wedges,texts=plt.pie(data.iloc[0],wedgeprops={"width": 0.4},
colors=['#5fc0a7','#ffe285','#f57125','#f7b1bf','#6dade2'])
labels = list(data.columns.values)
kw = dict(arrowprops=dict(arrowstyle="-"), zorder=0, va="center")
for i, p in enumerate(wedges):
ang = (p.theta2 - p.theta1) / 2.0 + p.theta1
# 根据角度的弧度计算 饼块均分点的坐标(引导线的起点)
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
# 设置引导线的连接方式
connectionstyle = "angle,angleA=0,angleB={}".format(ang)
kw["arrowprops"].update({"connectionstyle": connectionstyle})
# 绘制注释标签和引导线
plt.annotate(
data.columns[i],
xy=(x, y),
xytext=(1.35 * np.sign(x), 1.4 * y),
horizontalalignment=horizontalalignment,
**kw
)
plt.legend(loc=8,ncol=8,prop = {'size':9},labels=labels)
plt.title("负面信息占比图")
#ax.axis('equal')
plt.savefig('负面信息占比图.png')
plt.show()
这里的原代码只有环形图没有百分比,我想加入百分比,就在后面用画板加入autopct
# 绘制圆环图,并返回饼块对象
data=pd.read_excel(r'C:\Users\Administrator\Desktop\数据帮\数据处理\数据源\负面信息.xlsx')
#设置画板后,后面可以再次添加pie()的属性,
fig, ax = plt.subplots(figsize=(7,6))
#接下来得到一个元祖,看大神们是这样写的,我也不懂,但是这个和我想要的百分比环形图差一点,直接在这里加autopct会报错,显示打包错误,所以就用画板在后面增加pie属性
wedges,texts=plt.pie(data.iloc[0],wedgeprops={"width": 0.4},colors=['#5fc0a7','#ffe285','#f57125','#f7b1bf','#6dade2'])
labels = list(data.columns.values)
#标签带方框
bbox = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
# 构造annotate函数的**kwargs参数,设置引导线线型
kw = dict(arrowprops=dict(arrowstyle="-"), zorder=0,bbox=bbox va="center")
for i, p in enumerate(wedges):
ang = (p.theta2 - p.theta1) / 2.0 + p.theta1
# 根据角度的弧度计算 饼块均分点的坐标(引导线的起点)
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
# 设置引导线的连接方式
connectionstyle = "angle,angleA=0,angleB={}".format(ang)
kw["arrowprops"].update({"connectionstyle": connectionstyle})
# 绘制注释标签和引导线
plt.annotate(
data.columns[i],
xy=(x, y),
xytext=(1.35 * np.sign(x), 1.4 * y),
horizontalalignment=horizontalalignment,
**kw
)
#这里增加了我想要的pie属性,也就是百分比
ax.pie(data.iloc[0],autopct = '%0.2f%%',wedgeprops={"width": 0.5},pctdistance=0.7,colors=['#5fc0a7','#ffe285','#f57125','#f7b1bf','#6dade2'])
plt.legend(loc=8,ncol=8,prop = {'size':9},labels=labels)
plt.title("负面信息占比图")
plt.savefig('负面信息占比图.png')
plt.show()
中间的颜色我不指定的话,我这里会存在不对应现象,我就直接制定颜色了
也快可以对标签加上方框
bbox = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
,