[英]Python Matplotlib - Secondary axis multiple legends
我有一個具有輔助軸的 plot。 軸 1 繪制了兩個數據集。 軸 2 有一個數據集。 我可以得到兩個圖例(一個來自軸 1,一個來自軸 2),就像我想要的那樣 - 一個在另一個下方 plot 之外的右側。
我希望軸 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_anchor 的 y 值時,“data3”沒有出現在與其他兩個圖例一起出現的列中,而是與兩個圖例中的任何一個一起顯示在一行中。
謝謝
R
將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()
您可以使用線句柄和標簽手動構建圖例:
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)
Output:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.