Python 如何在Matplotlib中使用一个图例和删除的y轴标题制作MxN piechart绘图

Python 如何在Matplotlib中使用一个图例和删除的y轴标题制作MxN piechart绘图,python,matplotlib,plot,Python,Matplotlib,Plot,我有以下代码: import matplotlib.pyplot as plt plt.style.use('ggplot') import numpy as np np.random.seed(123456) import pandas as pd df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], columns=['x', 'y','z','w']) f, axes = plt.subplots(

我有以下代码:

import matplotlib.pyplot as plt
plt.style.use('ggplot')
import numpy as np
np.random.seed(123456)
import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], columns=['x', 'y','z','w'])

f, axes = plt.subplots(1,4, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    df[col].plot(kind='pie', autopct='%.2f', ax=ax, title=col, fontsize=10)
    ax.legend(loc=3)
    plt.ylabel("")
    plt.xlabel("")

plt.show()
这使得下面的图:

我怎样才能做到以下几点:

  • M=2 x N=2绘图时,M和N的值可能会改变
  • 删除y轴标题
  • 删除图例
  • 将其保存到文件中
具有共享图例的多个饼图 在我看来,在这种情况下,使用
matplotlib
手动绘图比使用
pandas
dataframe绘图方法更容易。这样你就有了更多的控制权。在打印所有饼图后,您可以仅向第一个轴添加图例:

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], 
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(1,4, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')

axes[0].legend(bbox_to_anchor=(0, 0.5))

fig.savefig('your_file.png') # Or whichever format you'd like
plt.show()

改用
pandas
绘图方法 但是,如果希望使用打印方法,请执行以下操作:

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(1,4, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    df[col].plot(kind='pie', legend=False, ax=ax, autopct='%0.2f', title=col,
                 colors=colors)
    ax.set(ylabel='', aspect='equal')

axes[0].legend(bbox_to_anchor=(0, 0.5))

fig.savefig('your_file.png')
plt.show()
两者产生相同的结果


重新排列子地块网格 如果您想要2x2或其他网格布局的绘图,
plt.subplot
将返回一个2D轴阵列。因此,您需要迭代
axes.flat
,而不是直接迭代
axes

例如:

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], 
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax, col in zip(axes.flat, df.columns):
    ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')

axes[0, 0].legend(bbox_to_anchor=(0, 0.5))

fig.savefig('your_file.png') # Or whichever format you'd like
plt.show()
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], 
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(nrows=2, ncols=3)
for ax in axes.flat:
    ax.axis('off')

for ax, col in zip(axes.flat, df.columns):
    ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')

axes[0, 0].legend(bbox_to_anchor=(0, 0.5))

fig.savefig('your_file.png') # Or whichever format you'd like
plt.show()

其他网格安排 如果希望栅格排列的轴数大于数据量,则需要隐藏任何未打印的轴。例如:

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], 
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax, col in zip(axes.flat, df.columns):
    ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')

axes[0, 0].legend(bbox_to_anchor=(0, 0.5))

fig.savefig('your_file.png') # Or whichever format you'd like
plt.show()
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], 
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(nrows=2, ncols=3)
for ax in axes.flat:
    ax.axis('off')

for ax, col in zip(axes.flat, df.columns):
    ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')

axes[0, 0].legend(bbox_to_anchor=(0, 0.5))

fig.savefig('your_file.png') # Or whichever format you'd like
plt.show()


省略标签 如果不希望标签在外部,请省略
饼图
标签
参数。但是,当我们这样做时,我们需要通过为艺术家传递艺术家和标签来手动构建图例。这也是演示使用
fig.legend
将单个图例与图形对齐的好时机。在这种情况下,我们将图例放在中间:

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax, col in zip(axes.flat, df.columns):
    artists = ax.pie(df[col], autopct='%.2f', colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')

fig.legend(artists[0], df.index, loc='center')

plt.show()

将百分比标签移到外部 同样,百分比标签的径向位置由
pctdistance
kwarg控制。大于1的值会将百分比标签移到饼图外部。但是,百分比标签(居中)的默认文本对齐方式假定它们位于饼图内部。一旦它们移出饼图,我们就需要使用不同的对齐约定

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

def align_labels(labels):
    for text in labels:
        x, y = text.get_position()
        h_align = 'left' if x > 0 else 'right'
        v_align = 'bottom' if y > 0 else 'top'
        text.set(ha=h_align, va=v_align)

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax, col in zip(axes.flat, df.columns):
    artists = ax.pie(df[col], autopct='%.2f', pctdistance=1.05, colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')
    align_labels(artists[-1])

fig.legend(artists[0], df.index, loc='center')

plt.show()

谢谢,但我也喜欢控制绘图矩阵,例如,g,M=2xN=2绘图或3x1绘图。我尝试修改为
fig,axes=plt。子绘图(2,2,figsize=(10,5))
,但不起作用。@neversaint-在这种情况下,您希望迭代
轴。flat
,因为
轴将是二维数组。您的第二个示例是什么?我试过了,但传说已经不复存在了。你能举个例子吗?@neversaint-我已经更新了答案来展示这两个例子。抱歉耽搁了。工作碍事:)