首页 > 解决方案 > 如何使用 Matplotlib 制作逐行饼图?

问题描述

我的数据框看起来像 -

state      value1       value2       value3
  a          20           65           15
  b          35           35           30
  c          30           25           45

我想要每个州的饼图(可能存在 20 个州)。我的代码如下 -

对于饼图 -

    for ind in df.index:
        fig, ax = plt.subplots(1,1)
        fig.set_size_inches(5,5)
        df.iloc[ind].plot(kind='pie', ax=ax, autopct='%1.1f%%')
        ax.set_ylabel('')
        ax.set_xlabel('')

但它不起作用。

标签: pythonpandasmatplotlibseaborn

解决方案


也许你应该:

  • 状态列设置为索引。
  • 创建具有足够Axes对象的单个图形(在我的示例中,我将所有这些对象放在一个列中。
  • 然后在相应的Axes对象中创建每个图。

就像是:

n = df.index.size
fig, axs = plt.subplots(n, 1, figsize=(5, 3 * n))
for i in range(n):
    df.iloc[i].plot(kind='pie', ax=axs[i], autopct='%1.1f%%')

对于您的数据样本,我得到:

在此处输入图像描述

当然,您可以进一步自定义特定参数,尤其是状态名称的可见性要被纠正。

或者,如果您想将绘图排列在 3 列中,请运行:

n = df.index.size; i = 0
nRows = math.ceil(n / 3)
fig, axs = plt.subplots(nRows, 3, figsize=(14, 4 * nRows))
for ax in axs.flat:
    if i < n:
        df.iloc[i].plot(kind='pie', ax=ax, autopct='%1.1f%%')
    else:
        ax.set_visible(False)
    i += 1

推荐阅读