2012-12-15 161 views
18

我有兩個sublot作爲2行和1列的圖。我可以添加一個好看的圖例與如何定位和對齊matplotlib圖形圖例?

fig.legend((l1, l2), ['2011', '2012'], loc="lower center", 
      ncol=2, fancybox=True, shadow=True, prop={'size':'small'}) 

然而,這個傳說是位於的中心,不低於的中心,因爲我想擁有它。現在,我可以得到我的軸座標與

axbox = ax[1].get_position() 

,並在理論上我應該能夠用一個元組指定祿關鍵字定位的傳說:

fig.legend(..., loc=(axbox.x0+0.5*axbox.width, axbox.y0-0.08), ...) 

這工作,圖例左對齊,以便loc指定圖例框的左邊緣/角落而不是中心。我搜索的關鍵字如alignhorizo​​ntalalignment等,但找不到任何。我也試圖獲得「傳奇位置」,但傳說沒有* get_position()*方法。我讀了關於* bbox_to_anchor *,但應用於數字圖例時無法理解它。這似乎是爲了斧頭傳說。

或者:我應該使用移位軸傳說嗎?但是,那麼爲什麼有傳奇人物呢?不知何故,它必須可以「中心對齊」一個圖例,因爲loc =「lower center」也是這樣做的。

感謝您的幫助,

馬丁

回答

25

在這種情況下,您可以使用軸爲圖legend方法。無論如何,bbox_to_anchor是關鍵。正如你已經注意到的,bbox_to_anchor指定了一個座標(或一個方框)的元組來放置圖例。當您使用bbox_to_anchor時,請考慮使用location kwarg來控制水平和垂直對齊。

區別在於座標元組是否被解釋爲座標軸或圖形座標。

作爲使用圖例的示例:

import numpy as np 
import matplotlib.pyplot as plt 

fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True) 

x = np.linspace(0, np.pi, 100) 

line1, = ax1.plot(x, np.cos(3*x), color='red') 
line2, = ax2.plot(x, np.sin(4*x), color='green') 

# The key to the position is bbox_to_anchor: Place it at x=0.5, y=0.5 
# in figure coordinates. 
# "center" is basically saying center horizontal alignment and 
# center vertical alignment in this case 
fig.legend([line1, line2], ['yep', 'nope'], bbox_to_anchor=[0.5, 0.5], 
      loc='center', ncol=2) 

plt.show() 

enter image description here

作爲使用軸方法的一個例子,嘗試是這樣的:

import numpy as np 
import matplotlib.pyplot as plt 

fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True) 

x = np.linspace(0, np.pi, 100) 

line1, = ax1.plot(x, np.cos(3*x), color='red') 
line2, = ax2.plot(x, np.sin(4*x), color='green') 

# The key to the position is bbox_to_anchor: Place it at x=0.5, y=0 
# in axes coordinates. 
# "upper center" is basically saying center horizontal alignment and 
# top vertical alignment in this case 
ax1.legend([line1, line2], ['yep', 'nope'], bbox_to_anchor=[0.5, 0], 
      loc='upper center', ncol=2, borderaxespad=0.25) 

plt.show() 

enter image description here

+0

謝謝,喬。這是澄清。經過進一步思考,我想對我原來的問題的答案應該是:「如果你想使用座標軸,使用axes.legend。」然而,出於好奇,我仍然懷疑loc關鍵字是否是控制圖例框中文本對齊的唯一方法?在許多其他matplotlib對象中,您可以提取補丁,線條等(請參閱boxplot文檔),並修改它們的屬性。這似乎不適用於圖例中的(文本對象),至少不是直截了當的。我對嗎? – maschu