2016-10-21 71 views
1

截至目前,我正在使用Matplotlib來生成圖。突出顯示圖例中的標籤,matplotlib

可以使用一些參數調整圖上的圖例(as mentioned in this guide)。但是我想在圖例中加入一些特定的內容,如下圖所示。 enter image description here

我想突出顯示圖例中的一個標籤(如現在使用MS塗料完成)。

如果還有其他突出顯示特定標籤的方法,那也是足夠的。

回答

1

通過FLab答案其實是相當合理的給出它可以是多麼痛苦回溯繪圖項目的座標。然而,公佈級別數字的要求通常是不合理的,並且看到matplotlib受到MS Paint的挑戰,對於回答這個問題是一個足夠好的動機。

讓我們從matplotlib畫廊爲出發點考慮this example

N = 100 
x = np.arange(N) 
fig = plt.figure() 
ax = fig.add_subplot(111) 
xx = x - (N/2.0) 
plt.plot(xx, (xx*xx)-1225, label='$y=x^2$') 
plt.plot(xx, 25*xx, label='$y=25x$') 
plt.plot(xx, -25*xx, label='$y=-25x$') 
legend = plt.legend() 
plt.show() 

一旦圖像已經繪就,我們可以回溯在legend實例中的元素,找出它們的座標。有與此相關的兩個難點:

  1. 我們將通過get_window_extent方法得到的是像素,而不是「數據」的座標,所以我們需要使用轉換函數的座標。轉換的一個很好的概述被給出here
  2. 尋找一個合適的邊界是棘手的。上面的legend實例有兩個有用的屬性,分別爲legend.legendHandleslegend.texts - 兩個列表,分別包含行藝術家和文本標籤列表。需要爲這兩個元素獲得邊界框,同時牢記實現可能不完美並且是後端特定的(參見this SO問題)。這是一個正確的方式來做到這一點,但它不是在這個答案的人,因爲...

..因爲幸運的是,在你的情況下,圖例框中,將其分割成與圖例中的行數相等的矩形,然後在屏幕上繪製其中一個矩形。下面我們將定義兩個函數,一個拿到傳說箱的數據座標,而另一個將其分割成塊,並繪製一個矩形根據指數:

from matplotlib.patches import Rectangle 

def get_legend_box_coord(ax, legend): 
    """ Returns coordinates of the legend box """ 
    disp2data = ax.transData.inverted().transform 
    box = legend.legendPatch 
    # taken from here: 
    # https://stackoverflow.com/a/28728709/4118756 
    box_pixcoords = box.get_window_extent(ax) 
    box_xycoords = [disp2data(box_pixcoords.p0), disp2data(box_pixcoords.p1)] 
    box_xx, box_yy = np.array(box_xycoords).T 
    return box_xx, box_yy 

def draw_sublegend_box(ax, legend, idx): 
    nitems = len(legend.legendHandles) 
    xx, yy = get_legend_box_coord(ax, legend) 
    # assuming equal spacing between legend items: 
    y_divisors = np.linspace(*yy, num=nitems+1) 
    height = y_divisors[idx]-y_divisors[idx+1] 
    width = np.diff(xx) 
    lower_left_xy = [xx[0], y_divisors[idx+1]] 

    legend_box = Rectangle(
      xy = lower_left_xy, 
      width = width, 
      height = height, 
      fill = False, 
      zorder = 10) 
    ax.add_patch(legend_box) 

現在,調用draw_sublegend_box(ax, legend, 1)產生以下plot: sublegendbox

請注意,只有在繪製圖形後才能對圖例進行註釋。