2015-01-07 42 views
3

我正在與matplotlib合作,並希望將我的傳說中的鍵更改爲正方形而不是矩形,例如,製作條形圖時。有沒有辦法指定這個?matplotlib:製作傳奇鍵方形

我現在擁有的一切:

enter image description here

我想要什麼:

enter image description here

謝謝!

回答

1

您可以定義您自己的圖例鍵。

我的答案中的條形圖使用matplotlib barchart demo創建。 (我已經刪除了錯誤欄)。 matplotlib legend guide解釋瞭如何定義一個類來用橢圓替換圖例鍵。我已修改該類以使用方塊(使用rectangle patches)。

import numpy as np 
from matplotlib.legend_handler import HandlerPatch 
import matplotlib.pyplot as plt 
import matplotlib.patches as mpatches 

# Define square (rectangular) patches 
# that can be used as legend keys 
# (this code is based on the legend guide example) 

class HandlerSquare(HandlerPatch): 
    def create_artists(self, legend, orig_handle, 
         xdescent, ydescent, width, height, fontsize, trans): 
     center = xdescent + 0.5 * (width - height), ydescent 
     p = mpatches.Rectangle(xy=center, width=height, 
           height=height, angle=0.0) 
     self.update_prop(p, orig_handle, legend) 
     p.set_transform(trans) 
     return [p]  

# this example is the matplotlib barchart example: 

N = 5 
menMeans = (20, 35, 30, 35, 27) 

ind = np.arange(N) # the x locations for the groups 
width = 0.35  # the width of the bars 

fig, ax = plt.subplots() 
rects1 = ax.bar(ind, menMeans, width, color='r') 

womenMeans = (25, 32, 34, 20, 25) 
rects2 = ax.bar(ind+width, womenMeans, width, color='y') 

# add some text for labels, title and axes ticks 
ax.set_ylabel('Scores') 
ax.set_title('Scores by group and gender') 
ax.set_xticks(ind+width) 
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) 

# append the new patches to the legend-call: 

ax.legend((rects1[0], rects2[0]), ('Men', 'Women'), 
      handler_map={rects1[0]: HandlerSquare(), rects2[0]: HandlerSquare()}) 

plt.show() 

在定義了class HandlerSquare,一個現在可以將此每個圖例項作爲第三個參數ax.legend通話。注意語法:

handler_map={rects1[0]: HandlerSquare(), rects2[0]: HandlerSquare()} 

handler_map必須是字典。

這會給你這樣的情節:

enter image description here

5

如果你想有一個非常快速和骯髒的解決方案,以獲得近似方形(可能需要一些微調取決於你的情節),你可以調整傳說中的handlelength克瓦格。繼Schorsch的解決方案(即一旦你有長方形的傳奇藝術家和相應的標籤列表):

ax.legend((rects1[0], rects2[0]), ('Men', 'Women'), handlelength=0.7) 

更多信息請參見matplotlib legend() docs

1

修改handlelength全局影響圖例中其他標記的寬度。因此該解決方案將不兼容於,例如,點和線補丁的組合。相反,您可以使用Line2D將一個方形點標記添加到圖例中。您只需將其關聯行設置爲零寬度:

rect1 = mlines.Line2D([], [], marker="s", markersize=30, linewidth=0, color="r") 
rect2 = mlines.Line2D([], [], marker="s", markersize=30, linewidth=0, color="y") 
ax.legend((rect1, rect2), ('Men', 'Women'))