matplotlib 二次轴多个图例

ax6ht2ek  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(72)

我有一个图,它有一个辅助轴,轴1有两个数据集,轴2有一个数据集。
我可以得到两个图例(一个来自轴1,一个来自轴2),就像我想要的那样-一个在另一个下面,在图的右边。
我希望轴1的第二个数据集的图例在上面两个图例的下面,但它显示在这两个图例的旁边。
我怎么才能让它工作?

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-',label='data1')
ax1.set_xlabel('time (s)')
ax1.legend(loc='lower left', bbox_to_anchor= (1.1, 0.7), ncol=2,
            borderaxespad=0, frameon=False)

ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r',label='data2')
ax2.legend(loc='lower left', bbox_to_anchor= (1.1, 0.6), ncol=2,
            borderaxespad=0, frameon=False)

data3 = [10000]*len(t)
ax1.plot(t,data3,'k--',label='data3')
ax1.legend(loc='lower left', bbox_to_anchor= (1.1, 0.5), ncol=2,
            borderaxespad=0, frameon=False)

plt.show()

当我更改bbox_to_锚的y值时,'data 3'不是与其他两个图例一起显示在列中,而是与两个图例中的任何一个一起显示在行中。

jk9hmnmh

jk9hmnmh1#

ncol=2更改为ncol=1以将图例项约束到同一列。

import numpy as np
import matplotlib.pyplot as plt

# constrained layout worked best for me, but you can change it back
fig = plt.figure(constrained_layout=True)
ax1 = fig.add_subplot(111)
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-',label='data1')
ax1.set_xlabel('time (s)')
ax1.legend(loc='lower left', bbox_to_anchor= (1.1, 0.7), ncol=1,
            borderaxespad=0, frameon=False)

ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r',label='data2')
ax2.legend(loc='lower left', bbox_to_anchor= (1.1, 0.6), ncol=1,
            borderaxespad=0, frameon=False)

data3 = [10000]*len(t)
ax1.plot(t,data3,'k--',label='data3')
ax1.legend(loc='lower left', bbox_to_anchor= (1.1, 0.5), ncol=1,
            borderaxespad=0, frameon=False)

plt.show()

mcvgt66p

mcvgt66p2#

您可以使用线句柄和标签手动构建图例:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-',label='data1')
ax1.set_xlabel('time (s)')

ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r',label='data2')
lh2, l2 = ax2.get_legend_handles_labels()

data3 = [10000]*len(t)
ax1.plot(t,data3,'k--',label='data3')
lh1, l1 = ax1.get_legend_handles_labels()

ax1.legend([lh1[0]]+lh2+[lh1[1]], 
           [l1[0]]+l2+[l1[1]], 
           loc='lower left', 
           bbox_to_anchor= (1.1, 0.4), 
           ncol=1,
           borderaxespad=0, 
           frameon=False)

输出量:

相关问题