我有一个包含 11 个散点图作为子图的图。我希望用图例(所有 11 个子图都相同)来替换第 12 个子图。有没有办法将图例放在那里并使其与子图的大小相同?
最佳答案
有点手动方法,但它是:
您可以使用 ax.clear()
和 ax.set_axis_off()
“删除”轴。然后,您可以创建具有特定颜色和标签的补丁,并根据它们在所需的轴中创建图例。
试试这个:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
# Create figure with subplots
fig, axes = plt.subplots(figsize=(16, 16), ncols=4, nrows=3, sharex=True, sharey=True)
# Plot some random data
for row in axes:
for ax in row:
ax.scatter(np.random.random(5), np.random.random(5), color='green')
ax.scatter(np.random.random(2), np.random.random(2), color='red')
ax.scatter(np.random.random(3), np.random.random(3), color='orange')
ax.set_title('some title')
# Clear bottom-right ax
bottom_right_ax = axes[-1][-1]
bottom_right_ax.clear() # clears the random data I plotted previously
bottom_right_ax.set_axis_off() # removes the XY axes
# Manually create legend handles (patches)
red_patch = mpatches.Patch(color='red', label='Red data')
green_patch = mpatches.Patch(color='green', label='Green data')
orange_patch = mpatches.Patch(color='orange', label='Orange data')
# Add legend to bottom-right ax
bottom_right_ax.legend(handles=[red_patch, green_patch, orange_patch], loc='center')
# Show figure
plt.show()
输出:
关于python - 有没有办法用图例替换 matplotlib 子图(而不是将图例放在子图之外)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60993466/