首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有办法将matplotlib子图替换为图例(而不是将图例放在子图之外)?

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

Stack Overflow用户
提问于 2020-04-02 22:04:35
回答 1查看 490关注 0票数 1

我有一个图,上面有11个散点图作为子图。我希望图例(在所有11个子图上相同)取代第12个子图。有没有办法将图例放在那里,并使其与子情节的大小相同?

Matplotlib scatter plot of 11 subplots

EN

回答 1

Stack Overflow用户

发布于 2020-04-02 22:27:40

一种手动的方法,但它是这样的:

您可以使用ax.clear()ax.set_axis_off()来“移除”轴。然后,您可以创建具有特定颜色和标签的修补程序,并基于它们在所需的ax中创建图例。

试试这个:

代码语言:javascript
复制
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()

输出:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60993466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档