python - 有没有办法用图例替换 matplotlib 子图(而不是将图例放在子图之外)?

标签 python matplotlib legend subplot

我有一个包含 11 个散点图作为子图的图。我希望用图例(所有 11 个子图都相同)来替换第 12 个子图。有没有办法将图例放在那里并使其与子图的大小相同?

Matplotlib scatter plot of 11 subplots

最佳答案

有点手动方法,但它是:

您可以使用 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()

输出:

enter image description here

关于python - 有没有办法用图例替换 matplotlib 子图(而不是将图例放在子图之外)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60993466/

相关文章:

python - 单击图例 python 散点图中的数据开/关

python - 在python中处理特定的异常类型

python - 从 Google 表格电子表格调用 python 脚本的好方法是什么?

Lennard-Jones 系统中的 Python 力图给出了 TypeError

matplotlib - 更改误差条大小

python - 如何更改 pyplot 中单个图例条目的字体大小?

python - seaborn/matplotlib 中的直方图显示 x 轴上的所有分箱数据索引

python - 停止 Python Multiprocessing BaseManager 'serve_forever' 服务器?

python - matplotlib 绘图窗口不会出现

r - 更改 ggplot2 中图例键中的符号