2015-06-30 153 views
2

下面的代碼的多行對準產生如下圖所示:Matplotlib圖例乳膠文本

import numpy as np 
import matplotlib.pyplot as plt 

xs = np.random.rand(100) 
ys = np.random.rand(100) 
r, p = 0.930, 1e-5 
label = '$T_m$\n$\\rho = %.3f, p = %.1e$'%(r, p) 

fig, ax = plt.subplots() 
ax.scatter(xs, ys, label=label) 
ax.legend() 
plt.show() 

enter image description here

我想中心的圖例文本,即'$T_m$'在第一行居中。我已經使用str.format小型的語言與不同的東西試圖像

label = '{0:{x}^25}\n{1:.3f}, {2:.1e}'.format('$T_m$', r, p, x=' ') 

我本以爲這工作,因爲下面給出

>>> print ax.get_legend_handles_labels() 
([<matplotlib.collections.PathCollection object at 0x7fa099286590>], 
[u'  $\\Delta T_{m}$  \n$\\rho=0.930, p=1.2 \\times 10^{-5}$']) 

但得到的空白標籤中剝離。我無法使用任何乳膠空間('\;''\\mbox{}')作爲填充字符,因爲它們是多個字符。我也嘗試在各個地方使用multialignment='center'關鍵字,但它不是ax.legend的合法kwarg。

如何在我的圖例文字中獲得居中的多行對齊?最終,我會在幾個圖例句柄中標籤文本可以在第二行(此處顯示)中包含更多字符,或者在第一行中包含更多字符(相反,如此處所示)。

我正在使用python 2.7.6和matplotlib 1.4.3。

回答

3

當你想出自己的關鍵是multialignment的論點。但是,它不是legend函數的參數,而僅僅是Text Atrists的一個參數。因此,關鍵是節約傳說的手柄,然後將該屬性格式爲每個文本元素:

leg = ax.legend() 
for t in leg.texts: 
    t.set_multialignment('center') 

結果:

enter image description here

+0

太好了,我知道這是簡單的東西。非常感謝。 – wflynny