matplotlib 具有共同x和y标签以及x轴下的共同图例的子图

6fe3ivhb  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(192)

我试图绘制一个子图,在图的底部显示一个通用图例,在一个通用x轴标签的下面,还有一个通用y轴标签。我有两种方法几乎可以让它工作,除了第一种方法是通用y轴标签与轴刻度标签重叠,而第二种方法我不知道如何让图例显示在图上(它挂在页面上)。
选项2,使用较新的supx/ylabel,在子情节和标签之间也放置了太多的空间-但我认为这是可以修复的(关于这一点有很多问题)。
这些只是示例图,实际的图在标签中使用更多的小数位,所以重叠是相当大的。我也可能设置图形大小来打印(和保存)图很好。

微波辐射计

import numpy as np
import matplotlib.pyplot as plt

# Some points to plot
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
z = np.sin((1.03* x) ** 2)

#option 1 - problem is with my real data the common y label is over the labels of the left hand plot

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 0].plot(x, z, '--')
axs[0, 1].plot(x, y)
axs[0, 1].plot(x, z, '--')
axs[1, 0].plot(x, -y)
axs[1, 0].plot(x, -z, '--')
axs[1, 1].plot(x, -y)
axs[1, 1].plot(x, -z, '--')

fig.add_subplot(111, frameon=False)
plt.tick_params(labelcolor='none', which='both', top=False, bottom=False, left=False, right=False)
plt.xlabel("The X label")
plt.ylabel("The Y label")

fig.subplots_adjust(bottom=0.2)
labels = ["A","B"]
fig.legend(labels,loc='lower center', ncol=len(labels), bbox_to_anchor=(0.55, 0))
fig.tight_layout()

# Option 2 - problem is I can't get the legend to show (it is off the page)
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 0].plot(x, z, '--')
axs[0, 1].plot(x, y)
axs[0, 1].plot(x, z, '--')
axs[1, 0].plot(x, -y)
axs[1, 0].plot(x, -z, '--')
axs[1, 1].plot(x, -y)
axs[1, 1].plot(x, -z, '--')

fig.supxlabel("The X label")
fig.supylabel("The Y label")

fig.subplots_adjust(bottom=0.2)
labels = ["A","B"]
fig.legend(labels,loc='lower center', ncol=len(labels), bbox_to_anchor=(0.55, 0))
fig.tight_layout()
utugiqy6

utugiqy61#

第一个选项几乎已经完成,将labelpad添加到ax.set_xlabel()ax.set_ylabel()调用应该可以解决您的问题。
这是最新版本。

# [...]

fig, axs = plt.subplots(2, 2, figsize=(16, 8), tight_layout=True)

# [...]

# Create the new axis for marginal X and Y labels
ax = fig.add_subplot(111, frameon=False)

# Disable ticks. using ax.tick_params() works as well
ax.set_xticks([])  
ax.set_yticks([])

# Set X and Y label. Add labelpad so that the text does not overlap the ticks
ax.set_xlabel("The X label", labelpad=20, fontsize=12)
ax.set_ylabel("The Y label", labelpad=40, fontsize=12)

# Set fig legend as you did
labels = ["A","B"]
fig.legend(labels, loc='lower center', ncol=len(labels), bbox_to_anchor=(0.55, 0))

相关问题