2017-04-11 48 views
0

我試圖把標籤在matplotlib.hlines每一行:如何設置標籤在matplotlib.hlines

from matplotlib import pyplot as plt 
plt.hlines(y=1, xmin=1, xmax=4, label='somelabel1') 
plt.hlines(y=2, xmin=2, xmax=5, label='somelabel2') 

我需要有兩個horizintal線,對每個「Y」軸標籤的陰謀線。 而不是它,我得到一個沒有標籤的情節,只有座標(見示例圖像)。是否可以將每行的標籤放入情節中?

enter image description here

回答

2

labelkwarg是指定在隨即出現在legend,不一定就行本身的字符串。如果您希望標籤出現在你的情節,你需要使用一個text對象,而不是

plt.hlines(y=1, xmin=1, xmax=4) 
plt.text(4, 1, ' somelabel1', ha='left', va='center') 

plt.hlines(y=2, xmin=2, xmax=5) 
plt.text(2, 2, 'somelabel2 ', ha='right', va='center') 

enter image description here

如果改爲希望爲這些特殊的y軸的標籤,你可以使用自定義格式。

import matplotlib.pyplot as plt 
import matplotlib.ticker as ticker 

plt.hlines(y=1, xmin=1, xmax=4) 
plt.hlines(y=2, xmin=2, xmax=5) 

def formatter(y, pos): 
    if y == 1: 
     return 'label1' 
    elif y == 2: 
     return 'label2' 
    else: 
     return y 

plt.gca().yaxis.set_major_formatter(ticker.FuncFormatter(formatter)) 

enter image description here

+0

有趣的,謝謝!是否有可能用這些字符串標籤替換y座標? – Vlad

+0

@Vlad我不確定你的意思。像y軸標籤一樣? – Suever

+0

是的,要在y軸上放置'somelabel1''1.0','somelabel2'而不是'2.0'等。可能我選擇了一種錯誤的情節類型,儘管我沒有找到任何適合我的東西目的( – Vlad