如何在大Pandas身上显示饼图

2024-06-28 19:29:36 发布

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

我一直在制作一个饼图来显示基于年份的数据。我已经尝试了很长时间,成功地实现了对行的切片:

df = pd.DataFrame(dict( Year = dates[:3],
        robbery = robbery[:3],
        fraud = fraud[:3],
        sexual = sexual[:3]
    ))
    fig, axes = plt.subplots(1,3, figsize=(12,8))
for ax, idx in zip(axes, df.index):
    ax.pie(df.loc[idx],explode=explode,shadow=True, labels=df.columns, autopct='%.2f%%')
    ax.set(ylabel='', title=idx, aspect='equal')
axes[0].legend(bbox_to_anchor=(0, 0.5))
plt.show()

enter image description here

但是我已经检查了这个链接到display pie chart,但是他们使用了numpy数组来实现图表。 在我的场景中,我坚持将所有数据一次性显示在饼图上,这是我的代码:

^{pr2}$

饼图如下所示:

enter image description here


Tags: 数据dataframedf切片pltaxpd年份
1条回答
网友
1楼 · 发布于 2024-06-28 19:29:36

我生成了一个示例9x3数据帧和一个3x3子块,然后在饼图中一次填充一行。在

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(low=0, high=10, size=(9, 3)),
      columns=['a', 'b', 'c'])

fig, axes = plt.subplots(3,3, figsize=(12,8))
for i in range(int(len(df.index)/3)):
    for j in range(int(len(df.index)/3)):
        idx = i * 3 + j
        ax = axes[i][j]
        ax.pie(df.loc[idx],shadow=True, labels=df.columns, autopct='%.2f%%')
        ax.set(ylabel='', title=idx, aspect='equal')
axes[0][0].legend(bbox_to_anchor=(0, 0.5))

plt.show()

相关问题 更多 >