如何在Matplotlib中使用一个图例和已删除的y轴标题制作MxN饼图 [英] How to make MxN piechart plots with one legend and removed y-axis titles in Matplotlib
问题描述
我有以下代码:
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
数据帧绘制方法更容易.这样,您就可以控制更多.绘制所有饼图后,可以仅在第一个轴上添加图例:
Multiple Pie Charts with a Shared Legend
In my opinion, it's easier to plot things manually with matplotlib
than to use a pandas
dataframe plotting method, in this case. That way you have more control. You can add a legend to only the first axes after plotting all of your pie charts:
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()
但是,如果您希望使用绘图方法:
However, if you'd prefer to use the plotting method:
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()
两者都会产生相同的结果.
Both produce identical results.
如果您希望图形以2x2或其他网格形式排列,则plt.subplots
将返回2D轴数组.因此,您需要遍历axes.flat
而不是直接遍历axes
.
If you'd like to have a 2x2 or other grid arrangement of plots, plt.subplots
will return a 2D array of axes. Therefore, you'd need to iterate over axes.flat
instead of axes
directly.
例如:
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()
如果您希望网格布置的轴数比您拥有的数据量更多,则需要隐藏所有未绘制的轴.例如:
If you'd like a grid arrangement that has more axes than the amount of data you have, you'll need to hide any axes that you don't plot on. For example:
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
相对于图形对齐单个图例的好时机.在这种情况下,我们将图例放在中间:
If you don't want the labels around the outside, omit the labels
argument to pie
. However, when we do this, we'll need to build up the legend manually by passing in artists and labels for the artists. This is also a good time to demonstrate using fig.legend
to align the single legend relative to the figure. We'll place the legend in the center, in this case:
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的值会将百分比标签移到饼图之外.但是,百分比标签(居中)的默认文本对齐方式假定它们位于饼图内部.一旦将它们移出饼图,我们将需要使用其他对齐约定.
Similarly, the radial position of the percentage labels is controlled by the pctdistance
kwarg. Values greater than 1 will move the percentage labels outside the pie. However, the default text alignment for the percentage labels (centered) assumes they're inside the pie. Once they're moved outside the pie, we'll need to use a different alignment convention.
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()
这篇关于如何在Matplotlib中使用一个图例和已删除的y轴标题制作MxN饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!