为了账号安全,请及时绑定邮箱和手机立即绑定

如何在饼图中添加框和标签,如下图所示

如何在饼图中添加框和标签,如下图所示

拉莫斯之舞 2022-01-18 21:30:02
尝试创建一个与下图完全相同的图形,并希望将其保存为 jpeg。我有一个名为“custpref”的数据框,如下所示tov_type            countInpatient               7Office Visit            6Appointment Schedule    1Allergy Sheet           1试过的代码如下: -def addPieGraph():# Create a list of colors (from iWantHue)colors = ["#6287da","#72ac5c","#8653aa","#bb7438","#b94b75"]# Create a pie chartplt.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 aboveplt.axis('equal')# View the plotplt.tight_layout()plt.title("Top 5 Visit Types                  Total = 15 Visits")plt.savefig(r"PieChart.png",bbox_inches="tight")plt.show()上面的代码绘制了饼图,只需要图例的帮助,指向它们的箭头,名称前面的计数和矩形框内的标签,图形周围有边框,如预期的输出。(来自上述数据框和预期图形的图例可能会随着每个图形的变化而变化。我希望我的图形完全符合预期的图像所示。)
查看完整描述

1 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

注意:虽然它不是您目标的完美再现,但我认为它已经足够接近您可以微调到您想要的结果。

我曾经gridspec创建两个单独的子图(pie_charttitle),添加了自定义注释行(改编自文档),并将子图格式化title为黑色,没有任何可见的刻度/刺。

绘图结果:

//img1.sycdn.imooc.com//61e6c0f3000140a105560376.jpg

使用的完整代码:


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()



查看完整回答
反对 回复 2022-01-18
  • 1 回答
  • 0 关注
  • 453 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信