使用带有自定义标签的饼图创建甜甜圈

2024-07-08 10:50:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理财务数据,我打算找出如何在我的数据上创建嵌套饼图。具体来说,我过滤了导出和导入产品数据,并为其呈现嵌套图。我确实为每个项目渲染了饼图,但我无法为数据获得正确的嵌套饼图或圆环图。我查看了SO上可能出现的帖子,但没有找到任何关于如何获得我的情节的线索

我的当前输出

import pandas as pd
from matplotlib import pyplot as plt

df5=df_from_gist_exp.groupby(['cty_ptn'])['qty1'].sum().nlargest(10)
df6=df_from_gist_imp.groupby(['cty_ptn'])['qty1'].sum().nlargest(10)
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.pie(df5, labels=df5.index, autopct='%1.0f%%', radius=1)
ax2.pie(df6, labels=df6.index, autopct='%1.0f%%', radius=1)
plt.axis('equal')
plt.tight_layout()
plt.show()

当前绘图

运行上述解决方案后,我得到了此绘图:

enter image description here

所需绘图

实际上,我希望使用相同的数据呈现此饼图或圆环图:

expected pie chart

我怎样才能得到这个图?有什么窍门可以让这一切发生吗?谢谢


Tags: 数据fromimport绘图dfaspltgist
1条回答
网友
1楼 · 发布于 2024-07-08 10:50:24

我只是编写了一个最小的代码来实现您想要的:

import matplotlib.pyplot as plt
import numpy as np

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
lbls = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]

# Intended to serve something like a global variable
class MyClass:
    i = -1

def func(pct, labels, vals):
    MyClass.i +=1
    # Returns absolute value against the default percentage
    # absolute = int(pct/100.*np.sum(vals))
    # Combine labels and values
    return "{:s}\n{:.0f} %".format(labels[MyClass.i], pct)


fig1, ax1 = plt.subplots()
# Pie wedgeprops with width being the donut thickness
ax1.pie(sizes, wedgeprops=dict(width=0.7), autopct=lambda pct: func(pct, lbls, sizes),
        shadow=True, startangle=90)
sumstr = 'Total = '+str(np.sum(sizes))
# String on the donut center
ax1.text(0., 0., sumstr, horizontalalignment='center', verticalalignment='center')
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

这将生成以下图表:

enter image description here

相关问题 更多 >

    热门问题