2012-12-02 56 views
2

我有這樣的情節:多維數據和情節的傳說

data = {'User 1': [1,2,3], 'User 2': [5, 8, 10], 'User 3': [80, 75, 100], 'User 4': [65, 80, 45]} 
characteristics = [('commits', 'r'), ('intended h', 'g'), ('actual h', 'b')] 

n_bars = (len(characteristics)+1)*len(data) 

fig = plt.figure(figsize=(5,5)) 
ax = fig.add_axes([0.15, 0.15, 0.65, 0.7]) 
ax.spines['right'].set_color('none') 
ax.spines['top'].set_color('none') 
ax.set_yticklabels(data.keys()) 
ax.set_yticks(np.arange(len(characteristics)/2, n_bars, len(data))) 

pers_id = 0 
bar_id = 0 

for name, data in data.iteritems(): 
    for char_id, characteristic in enumerate(characteristics): 
     ax.barh(bar_id, data[char_id], facecolor=characteristic[1]) 
     bar_id = bar_id + 1 
    ax.barh(bar_id, 100, facecolor='white', linewidth=0) 
    bar_id += 1 
    pers_id += 1 

plt.savefig('perf.png') 
plt.show() 

enter image description here

唯一的大的功能,我還需要是添加一個傳奇右上角,與characteristics[i][0]和指示標籤顏色從characteristics[i][0]

我將如何得到這個工作?

回答

2

pandas有一些數據結構和方法來處理和情節這樣的數據:

In [89]: import pandas as pd 

In [90]: df = pd.DataFrame(data).T 

In [91]: df.columns = [c[0] for c in characteristics] 

In [92]: df 
Out[92]: 
     commits intended h actual h 
User 1  1   2   3 
User 2  5   8  10 
User 3  80   75  100 
User 4  65   80  45 

In [93]: colors = [c[1] for c in characteristics] 

In [94]: df.sort_index(ascending=False).plot(kind='barh', color=colors) 

pandas_barh

1
import matplotlib.pyplot as plt 
import numpy as np 
import collections 

data = {'User 1': [1,2,3], 'User 2': [5, 8, 10], 'User 3': [80, 75, 100], 
     'User 4': [65, 80, 45]} 
characteristics = [('commits', 'r'), ('intended h', 'g'), ('actual h', 'b')] 

n_bars = (len(characteristics)+1)*len(data) 

fig = plt.figure(figsize=(5,5)) 
ax = fig.add_axes([0.15, 0.15, 0.65, 0.7]) 
ax.spines['right'].set_color('none') 
ax.spines['top'].set_color('none') 
ax.set_yticklabels(data.keys()) 
ax.set_yticks(np.arange(len(characteristics)/2, n_bars, len(data))) 

pers_id = 0 
bar_id = 0 

artists = collections.deque(maxlen = len(characteristics)) 
labels = collections.deque(maxlen = len(characteristics)) 
for name, data in data.iteritems(): 
    for char_id, characteristic in enumerate(characteristics): 
     artist, = ax.barh(bar_id, data[char_id], facecolor=characteristic[1]) 
     artists.append(artist) 
     labels.append(characteristic[0]) 
     bar_id = bar_id + 1 
    ax.barh(bar_id, 100, facecolor='white', linewidth=0) 
    bar_id += 1 
    pers_id += 1 

plt.legend(artists, labels, loc = 'best') 
# plt.savefig('perf.png') 
plt.show() 

產生 enter image description here

+0

顯然,相傳是數據的外部繪製矩形...如何實現這一目標? – Flavius

+0

據我所知,matplotlib * always *在「數據繪圖矩形」內繪製圖例。如果它覆蓋了你的一些數據,你可以增加'xlim',所以圖例位於最大值的右邊。 – unutbu

+0

@弗萊維斯:爲什麼這是顯而易見的? @unutbu:我想你可以使用'leg = ax.legend(artists,labels,loc = 2,bbox_to_anchor =(1.05,1.0)); fig.savefig('perf.png',bbox_extra_artists =(leg,),bbox_inches ='tight')'做到這一點。 – DSM