python - 如何在饼图中添加框和标签,如下图所示
问题描述
尝试创建一个与下图完全相同的图形,并希望将其保存为 jpeg。我有一个名为“custpref”的数据框,如下所示
tov_type count
Inpatient 7
Office Visit 6
Appointment Schedule 1
Allergy Sheet 1
试过的代码如下: -
def addPieGraph():
# Create a list of colors (from iWantHue)
colors = ["#6287da","#72ac5c","#8653aa","#bb7438","#b94b75"]
# Create a pie chart
plt.pie(
# using data total)arrests
custpref['cnt'],
# with the labels being officer names
labels=custpref['tov_type'],
# with no shadows
shadow=False,
# with colors
colors=colors,
# with the start angle at 90%
startangle=90,
)
# View the plot drop above
plt.axis('equal')
# View the plot
plt.tight_layout()
plt.title("Top 5 Visit Types Total = 15 Visits")
plt.savefig(r"PieChart.png",bbox_inches="tight")
plt.show()
预期结果:- 饼图的预期外观
上面的代码绘制了饼图,只需要图例的帮助,指向它们的箭头,名称前面的计数和矩形框内的标签,图形周围有边框,如预期的输出。
(来自上述数据框和预期图形的图例可能会随着每个图形的变化而变化。我希望我的图形完全符合预期的图像所示。)
解决方案
注意:虽然它不是您目标的完美再现,但我认为它已经足够接近您,可以微调到您想要的结果。
我曾经gridspec
创建两个单独的子图(pie_chart
和title
),添加了自定义注释行(改编自文档),并将子图格式化title
为黑色,没有任何可见的刻度/刺。
绘图结果:
使用的完整代码:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import gridspec
custpref=pd.DataFrame({'tov_type':['Inpatient','Office Visit','Appointment Schedule','Allergy Sheet'],'count':[7,6,1,1]})
fig=plt.figure(figsize=(6,4))
gs1 = gridspec.GridSpec(1,1,
left=0.1,right=0.7,
bottom=0.1,top=0.7,
)
gs2 = gridspec.GridSpec(1,1,
left=0.05,right=0.95,
bottom=0.9,top=1.0,
)
pie_ax=fig.add_subplot(gs1[0])
title_ax=fig.add_subplot(gs2[0])
# Create a list of colors (from iWantHue)
colors = ["#6287da","#72ac5c","#8653aa","#bb7438","#b94b75"]
# Create a pie chart
wedges, texts = pie_ax.pie(
# using data total)arrests
custpref['count'],
# with no shadows
shadow=False,
# with colors
colors=colors,
# with the start angle at 90%
startangle=90,
)
bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(xycoords='data', textcoords='data', arrowprops=dict(arrowstyle="-"), zorder=0, va="center")
for i, p in enumerate(wedges):
ang = (p.theta2 - p.theta1)/2. + 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,"color":colors[i]})
pie_ax.annotate(custpref['tov_type'][i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
horizontalalignment=horizontalalignment, **kw)
# View the plot drop above
pie_ax.axis('equal')
title_ax.set_facecolor('k')
title_ax.text(0.5,0.5,"Top 5 Visit Types Total = 15 Visits",
ha="center",va="center",transform=title_ax.transAxes,color="w")
for side in ['top', 'bottom', 'left', 'right']:
title_ax.spines[side].set_visible(False)
title_ax.axes.get_xaxis().set_visible(False)
title_ax.axes.get_yaxis().set_visible(False)
plt.savefig(r"PieChart.png",bbox_inches="tight")
plt.show()
推荐阅读
- c - C - rand() 在循环中
- ruby - 有人可以解释一下代码是如何工作的
- r - 如何更正一个简单的函数:获取错误替换的长度为零
- java - 尝试使用 Maven 解决多个存储库中缺少的依赖项
- javascript - 转换嵌套对象
- dryioc - 注册一个服务,以便 Resolve(args) 将 args 作为愚蠢的位置参数传递?
- python - Django 为 ordering_fields 使用计算字段
- cordova - 防止包含 target=“_blank” 链接的 iframe 接管应用程序
- pandas - 使用 DateOffset 重新采样可以给出 NotImplementedError
- redis - BITOP NOT 在 Redis 5.0.5 中无法正常工作