gpt4 book ai didi

matplotlib - matplotlib 子图中的图例位置

转载 作者:行者123 更新时间:2023-12-04 02:50:03 31 4
gpt4 key购买 nike

我正在尝试在 (6X3) 网格上创建子图。我对图例的位置有疑问。图例对所有子图都是通用的。 lgend 现在与 y 轴标签重叠

我尝试删除 constrained_layout=True 选项。但这在图例和子图之间保留了很多空白。

import numpy as np
import matplotlib.pyplot as plt
#plt.rcParams["font.family"] = "Times New Roman"
#plt.rcParams.update({'font.size': 12})

font = {'family' : 'Times New Roman',
'size' : 14}
plt.rc('font', **font)


t = np.linspace(0,10, num=200)
fig, axs = plt.subplots(6, 3, figsize=(12,16))#, constrained_layout=True)
i = 0 # i = 0 for x = 0.25; i = 3 for x = -0.25
j = 6 # j = 6 for x = 0.25; j = 9 for x = -0.25
#%%
solution = np.loadtxt(open("sequential_legs=01.csv", "rb"), delimiter=",", skiprows=0)
axs[0, 0].plot(t, solution[:,i],'r-')
axs[0, 0].plot(t, solution[:,i+1],'g-')
axs[0, 0].plot(t, solution[:,i+2],'b-')
axs[0, 0].plot(t, solution[:,j],'r--')
axs[0, 0].plot(t, solution[:,j+1],'g--')
axs[0, 0].plot(t, solution[:,j+2],'b--')
axs[0, 0].set_title('DNN-S (p = 1)', fontsize=14)
axs[0, 0].set_xlim([0, 10])
(repeated for each grid)
line_labels = ["$y_1$ (True)","$y_2$ (True)", "$y_3$ (True)", "$y_1$ (ML-Pred)","$y_2$ (ML-Pred)", "$y_3$ (ML-Pred)"]
plt.figlegend( line_labels, loc = 'lower center', borderaxespad=0.1, ncol=6, labelspacing=0., prop={'size': 13} ) #bbox_to_anchor=(0.5, 0.0), borderaxespad=0.1,

for ax in axs.flat:
ax.set(xlabel='Time', ylabel='Response')

for ax in axs.flat:
ax.label_outer()

fig.savefig('LSE_X=025.pdf', bbox_inches = 'tight')

enter image description here

最佳答案

constrained_layout does not take figure legends into account .我目前在这里看到的最简单的选择是使用 tight_layout 使子图在图中很好地分布,然后之后手动为图例添加一些空间。

import matplotlib.pyplot as plt

fig, axs = plt.subplots(6, 3, figsize=(12,8), sharex=True, sharey=True,
constrained_layout=False)

labels = [f"Label {i}" for i in range(1,5)]

for ax in axs.flat:
for i, lb in enumerate(labels):
ax.plot([1,2], [0,i+1], label=lb)
ax.set_xlabel("x label")
ax.label_outer()

fig.tight_layout()
fig.subplots_adjust(bottom=0.1) ## Need to play with this number.

fig.legend(labels=labels, loc="lower center", ncol=4)

plt.show()

enter image description here

关于matplotlib - matplotlib 子图中的图例位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55465653/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com