【问题标题】:Is there a way to replace a matplotlib subplot with a legend (rather than have the legend outside the subplots)?有没有办法用图例替换 matplotlib 子图(而不是将图例放在子图之外)?
【发布时间】:2020-07-14 12:51:24
【问题描述】:

我有一个带有 11 个散点图的图作为子图。我希望图例(所有 11 个子图都相同)替换第 12 个子图。有没有办法把图例放在那里,让它和子图一样大?

Matplotlib scatter plot of 11 subplots

【问题讨论】:

标签: python matplotlib legend subplot


【解决方案1】:

一种手动​​方法,但这里是:

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

输出:

【讨论】:

  • 知道如何为图例上方的子图添加 xtick 标签吗?
猜你喜欢
  • 1970-01-01
  • 2017-10-05
  • 2012-02-16
  • 2021-11-18
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
  • 2014-04-24
相关资源
最近更新 更多