2014-06-18 38 views
0

我需要繪製數據的條形圖,標籤太長而不適合在x軸上顯示標記。我希望在圖例中包含標籤,但無法從圖例中移除顏色(包括顏色使圖例雜亂無章)。下面是一些示例代碼:沒有顏色的圖例的條形圖

import matplotlib.pyplot as plt 

data_dic={1:'1:Text 1',2:'2:Text 2',3:'3:Text 3',4:'4:Text 4'} 
ax1 = plt.subplot(111) 
xval = [1,2,3,4] 
yval = [ 22., 13., 21., 6.] 
for j in range(len(xval)): 
    ax1.bar(xval[j], yval[j], width=0.8, bottom=0.0, align='center', color='k', label=data_dic[xval[j]]) 
ax1.set_xticks(xval) 
ax1.legend() 
plt.show() 

enter image description here

謝謝!

回答

1

您可以創建一個不顯示顏色或任何標記的圖例,方法是繪製不帶標記或線條的標記並將標記與該圖標相關聯。下面是它如何與你的例子:

import matplotlib.pyplot as plt 

data_dic={1:'1:Text 1',2:'2:Text 2',3:'3:Text 3',4:'4:Text 4'} 
ax1 = plt.subplot(111) 
xval = [1,2,3,4] 
yval = [ 22., 13., 21., 6.] 
for j in range(len(xval)): 
    ax1.bar(xval[j], yval[j], width=0.8, bottom=0.0, align='center', color='k') 
    ax1.plot(1,1,label = data_dic[xval[j]],marker = '',ls ='') #plot with not marker or line 
ax1.set_xticks(xval) 
ax1.legend(frameon = False) 
plt.show() 

legend with no markers

你也可以使用text而不是legend,因爲你不需要與標誌物相關的文字。

+0

大 - 簡單而有效的。謝謝! – shadowprice

0

設置handlength=0讓你關閉。一個技巧是,即使邊緣被繪製,所以你需要爲標記設置透明的邊緣顏色。還要調整handletextpad,以便文字在圖例框中居中。例如,用下面的更換圖例行:

H, L = ax1.get_legend_handles_labels() 
p = Rectangle((0, 0), 1, 1, fc='r', ec=(1, 0, 0, 0)) 
ax1.legend([p]*4, L, handlelength=0, handletextpad=0) 

enter image description here