2012-12-06 19 views
3

當情節中有很多線條時,圖例並不總是標註它們的最佳方式。我經常做這樣的事情來標記劇情右邊緣的線條:當軸線限制改變時,沒有圖例的線條很好?

def p(): 
    fig, ax = plt.subplots() 
    x = arange(1, 3, 0.01) 
    for i,c in zip(range(4), ('r','g','b','m')): 
     ax.plot(x, x**i, c=c, lw=2) 
     ax.annotate('$x^%d$' % i, (1.01, x[-1]**i), 
        xycoords=('axes fraction', 'data'), color=c) 
    return ax 

這只是一個簡單的例子,只有幾行。它看起來像這樣:

>>> p() 

enter image description here

不過,如果我需要改變劇情的限制,標籤是在錯誤的地方:

>>> p().set_xlim((1.0, 2.0)) 

enter image description here

問題:什麼是最簡單的方法直接標記在一個情節(不使用圖例)的情節在一個通過改變軸極限不會破壞的方式?

+0

我不我知道......但我很好奇你爲什麼不把p()作爲軸極限的函數,並且每次調用它é你需要一個新的情節? – Pete

+0

你可能是對的,那將是最簡單的方法。但是,如果標籤「附加」到交互式使用的線條上,那很好。 – RCL

回答

2

你只需要做到這一點:

xlim = 2.0  
def p(): 
     fig, ax = plt.subplots() 
     x = np.arange(1, 3, 0.01) 
     for i,c in zip(range(4), ('r','g','b','m')): 
      ax.plot(x, x**i, c=c, lw=2) 
      ax.annotate('$x^%d$' % i, (1.01, min(x, key=lambda x:abs(x-xlim))**i), 
         xycoords=('axes fraction', 'data'), color=c) 
     return ax 

差異

min(x, key=lambda x:abs(x-xlim)) 

這件事找到列表X附近號碼輸入數字

​​

相關問題