【发布时间】:2020-07-14 12:51:24
【问题描述】:
我有一个带有 11 个散点图的图作为子图。我希望图例(所有 11 个子图都相同)替换第 12 个子图。有没有办法把图例放在那里,让它和子图一样大?
【问题讨论】:
-
当然,这是how-to-put-the-legend-out-of-the-plot 在“专用子图轴内的图例”标题下提到的解决方案之一。
标签: python matplotlib legend subplot
我有一个带有 11 个散点图的图作为子图。我希望图例(所有 11 个子图都相同)替换第 12 个子图。有没有办法把图例放在那里,让它和子图一样大?
【问题讨论】:
标签: python matplotlib legend subplot
一种手动方法,但这里是:
您可以使用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()
输出:
【讨论】: