Matplotlib ax1 ax2双轴时绘图外的图例

Matplotlib ax1 ax2双轴时绘图外的图例,matplotlib,Matplotlib,我正在申请在情节外放置图例。这里的主要区别是有ax1和ax2两个轴 bbox\u to\u锚定中的x值在以下MWE中设置为0.89 可以看出,图例框不会显示每种颜色的整个字符串标签: MWE: 减小该x值并注释掉bbox\u inches='tight'部分,得到以下结果: 对于bbox\u to\u anchor=(0.85,0.5),结果如下: 对于bbox\u to\u anchor=(0.80,0.5),结果如下: 对于bbox\u to\u anchor=(0.7,0.

我正在申请在情节外放置图例。这里的主要区别是有
ax1
ax2
两个轴

bbox\u to\u锚定
中的
x值
在以下MWE中设置为
0.89

可以看出,图例框不会显示每种颜色的整个字符串标签:

MWE:

减小该
x值
并注释掉
bbox\u inches='tight'
部分,得到以下结果:

  • 对于
    bbox\u to\u anchor=(0.85,0.5)
    ,结果如下:

  • 对于
    bbox\u to\u anchor=(0.80,0.5)
    ,结果如下:

  • 对于
    bbox\u to\u anchor=(0.7,0.5)
    ,结果如下:

将其设置为
0.85
0.80
,直到合适为止。@importanceofbeingerest非常感谢您的评论。我已将其设置为
0.85
0.80
(请参见编辑)。哦,是的,这当然只能在不使用
bbox\u inches='tight'
@ImportanceOfBeingErnest时起作用。非常感谢。我试着注释出
bbox\u inches='tight'
,我得到了新编辑中显示的两个图是,因此连续降低该数字,直到图例出现在画布中。
import matplotlib.pyplot as plt
import numpy as np

suptitle_label = "rrrrrrrr @ ttttt yyyyyyy. uuuuuuuuuuuuuuuuuu\n$[$Xx$_{2}$Yy$_{7}]^{-}$ + $[$XxYy$_{2}$(cccc)$_{2}]^{+}$ JjYy model"

# Plotting 
fig, ax1 = plt.subplots()

ax1.set_xlabel('Time')
ax1.set_ylabel('y1label')

new_time = np.linspace(1, 8, 100)
j_data = [np.linspace(1, 4, 100), np.linspace(1, 5, 100), np.linspace(1, 6, 100), np.linspace(1, 7, 100)]

sorted_new_LABELS_fmt = ['$[$XxYy$_{2}$(cc)$_{2}]^{+}$', '$[$Xx$_{2}$Yy$_{7}]^{-}$', '$[$XxYy$_{4}]^{-}$', '$[$Xx$_{2}$Yy$_{5}$(cc)$_{2}]^{+}$']

sorted_new_LABELS_colors = ['green', 'red', 'blue', 'orange']

for j,k,c in zip(j_data, sorted_new_LABELS_fmt, sorted_new_LABELS_colors):
    ax1.plot(new_time, j, label='%s' % k, color='%s' %c)


All_e_chunks_n = np.linspace(-850, -860, 100)
ax2 = ax1.twinx()

ax2.set_ylabel('y2label')
ax2.plot(new_time, All_e_chunks_n, 'grey', alpha=0.6, linewidth=2.5, label='y2')

# Shrink cccrent axis 
box = ax1.get_position()
ax1.set_position([box.x0, box.y0, box.width * 0.9, box.height])

# Put the legend:
fig.legend(loc='center left', bbox_to_anchor=(0.89, 0.5)) 

fig.suptitle(suptitle_label, fontsize=15)                                                              

fig.savefig('mwe.pdf', bbox_inches='tight')