Python 如何向饼图添加框和标签,如下图所示
正在尝试创建一个与下图完全相同的图形,并希望将其另存为jpeg。 我有一个名为“custpref”的数据帧,如下所示Python 如何向饼图添加框和标签,如下图所示,python,matplotlib,Python,Matplotlib,正在尝试创建一个与下图完全相同的图形,并希望将其另存为jpeg。 我有一个名为“custpref”的数据帧,如下所示 tov_type count Inpatient 7 Office Visit 6 Appointment Schedule 1 Allergy Sheet 1 测试代码如下:- def addPieGraph(): # Create a list of colors (from
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()
使用的完整代码:
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()
注意:虽然这不是对你的目标的完美再创造,但我认为这已经足够让你微调到你想要的结果
我使用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()
使用的完整代码:
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()
这对我来说是可行的,但在某些情况下,我会遇到错误“给定的线不相交。请验证角度不相等或相差180度。”有解决方案吗?@P.Natu-Hmm,由于使用了
紧密布局()
,这似乎是matplotlib 3.x中的一个错误;如果您导入matplotlib,您的打印内容是什么(matplotlib.\uuuu版本)?它是3.0.3。我也尝试了不同的开始角度。在这种情况下,设置startangle=-40有效。在其他此类情况下,它是否有效。。这对我来说是可行的,但在某些情况下,我会遇到错误“给定的线不相交。请验证角度不相等或相差180度。”有解决方案吗?@P.Natu-Hmm,由于使用了紧密布局()
,这似乎是matplotlib 3.x中的一个错误;如果您导入matplotlib,您的打印内容是什么(matplotlib.\uuuu版本)?它是3.0.3。我也尝试了不同的开始角度。在这种情况下,设置startangle=-40有效。在其他此类情况下,它是否有效。。