Matplotlib子图中的图例位置

w8rqjzmb  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(109)

我试图在(6X3)网格上创建子图。我遇到图例位置问题。图例对所有子图都是通用的。图例现在与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')

t30tvxxf

t30tvxxf1#

constrained_layout没有考虑图例。我目前看到的最简单的选择是使用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()

相关问题