Matplotlib:如何调整第二个图例的zorder?

pbr*_*ach 3 python matplotlib

这是一个重现我的问题的示例:

import matplotlib.pyplot as plt
import numpy as np

data1,data2,data3,data4 = np.random.random(100),np.random.random(100),np.random.random(100),np.random.random(100)

fig,ax = plt.subplots()

ax.plot(data1)
ax.plot(data2)
ax.plot(data3)

ax2 = ax.twinx()
ax2.plot(data4)

plt.grid('on')
ax.legend(['1','2','3'], loc='center')
ax2.legend(['4'], loc=1)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我怎样才能使图例位于中心以绘制在线条上方?

Gre*_*reg 5

要获得您想要的确切信息,请尝试以下操作。注意,我已经修改了代码,以在生成图时定义标签以及颜色,以免重复出现蓝线。

import matplotlib.pyplot as plt
import numpy as np

data1,data2,data3,data4 = (np.random.random(100),
                           np.random.random(100),
                           np.random.random(100),
                           np.random.random(100))

fig,ax = plt.subplots()

ax.plot(data1, label="1", color="k")
ax.plot(data2, label="2", color="r")
ax.plot(data3, label="3", color="g")

ax2 = ax.twinx()
ax2.plot(data4, label="4", color="b")

# First get the handles and labels from the axes
handles1, labels1 = ax.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()

# Add the first legend to the second axis so it displaysys 'on top'
first_legend = plt.legend(handles1, labels1, loc='center')
ax2.add_artist(first_legend)

# Add the second legend as usual
ax2.legend(handles2, labels2)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

现在,我要补充一点,如果只使用一个图例将所有行添加到该图例中,将会更加清楚。在本SO帖子对此进行了描述,并且在上面的代码中可以轻松实现

ax2.legend(handles1+handles2, labels1+labels2)
Run Code Online (Sandbox Code Playgroud)

但显然,您可能有自己的理由想要两个传说。