具有共享图例的多个饼图
在我看来,在这种情况下,使用 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()
改用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.subplots 将返回一个二维轴数组。因此,您需要直接迭代 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()
省略标签
如果您不希望标签环绕在外面,请省略 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()
将百分比标签移到外面
同样,百分比标签的径向位置由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()