简体   繁体   English

如何使用 Matplotlib 制作逐行派 plot?

[英]How to make a row-wise pie plot using Matplotlib?

My dataframe looks like -我的 dataframe 看起来像 -

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

I want a pie chart for each state( may be 20 states are present).我想要每个州的饼图(可能存在 20 个州)。 My code is given below -我的代码如下 -

For pie chart -对于饼图 -

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

But it does not work.但它不起作用。

Probably you should:也许你应该:

  • Set state column as the index.state列设置为索引。
  • Create a single figure with enough Axes objects (in my example I put all of them in a single column.创建具有足够Axes对象的单个图形(在我的示例中,我将所有这些对象放在一个列中。
  • Then create each plot in corresponding Axes object.然后在相应的Axes object 中创建每个 plot。

Something like:就像是:

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%%')

For your data sample I got:对于您的数据样本,我得到:

在此处输入图像描述

Of course, you can further customize particular parameters, espacially visibility of state names is to be corrected.当然,您可以进一步自定义特定参数,尤其是 state 名称的可见性需要更正。

Or if you want to arrange your drawings in 3 columns, run:或者,如果您想将绘图排列在 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM