如何在Matplotlib中制作带有一个图例的MxN饼图和删除的y轴标题

我有以下代码:

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

这使得以下情节:

enter image description here

我该如何做到以下几点:

> M = 2 x N = 2绘图,M和N的值可以改变.
>删除y标题轴
>删除传说
>将其保存到文件中

最佳答案
具有共享图例的多个饼图

在我看来,在这种情况下,使用matplotlib手动绘制事物比使用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):
    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()

enter image description here

请使用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()

两者产生相同的结果.

重新排列子图网格

如果你想要一个2×2或其他网格排列的图,plt.subplots将返回一个2D数组的轴.因此,您需要直接迭代axes.flat而不是轴.

例如:

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

enter image description here

其他网格安排

如果您希望网格排列的轴数多于您拥有的数据量,则需要隐藏任何未绘制的轴.例如:

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

enter image description here

省略标签

如果您不希望外围的标签,请省略pie的labels参数.但是,当我们这样做时,我们需要通过为艺术家传递艺术家和标签来手动建立图例.这也是使用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()

enter image description here

外部移动百分比标签

类似地,百分比标签的径向位置由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()

enter image description here

转载注明原文:如何在Matplotlib中制作带有一个图例的MxN饼图和删除的y轴标题 - 代码日志