2012-12-18 63 views
0

非常新手問題:蟒蛇柱狀圖中

我需要借鑑元組的列表柱狀圖。第一個元素是x軸的名稱(分類),第二個元素是float類型(對於y軸)。我也想按降序排列這些酒吧,並添加一個趨勢線。下面是一些示例代碼:

In [20]: popularity_data 
Out[20]: 
[('Unknown', 10.0), 
(u'Drew E.', 240.0), 
(u'Anthony P.', 240.0), 
(u'Thomas H.', 220.0), 
(u'Ranae J.', 150.0), 
(u'Robert T.', 120.0), 
(u'Li Yan M.', 80.0), 
(u'Raph D.', 210.0)] 

回答

-1

你可以使用ASCII字符只是代表了吧,或者你可以檢查出matplotlib ...

0

你應該使用字典,它更容易使用。這讓你在酒吧降序排列:

popularity_data = { 
    'Unknown': 10.0, 
    u'Drew E.': 240.0, 
    u'Anthony P.': 240.0, 
    u'Thomas H.': 220.0, 
    u'Ranae J.': 150.0, 
    u'Robert T.': 120.0, 
    u'Li Yan M.': 80.0, 
    u'Raph D.': 210.0 
} 

for y in reversed(sorted(popularity_data.values())): 
    k = popularity_data.keys()[popularity_data.values().index(y)] 
    print k + ':', y 
    del popularity_data[k] 

您可以添加使用matplotlib趨勢線,爲Aleksander S建議。

而且,如果你喜歡,你可以把它保存在一個元組列表,你原本是這樣的:

popularity_data = { 
    'Unknown': 10.0, 
    u'Drew E.': 240.0, 
    u'Anthony P.': 240.0, 
    u'Thomas H.': 220.0, 
    u'Ranae J.': 150.0, 
    u'Robert T.': 120.0, 
    u'Li Yan M.': 80.0, 
    u'Raph D.': 210.0 
} 

descending = [] 
for y in reversed(sorted(popularity_data.values())): 
    k = popularity_data.keys()[popularity_data.values().index(y)] 
    descending.append(tuple([k, y])) 
    del popularity_data[k] 

print descending 
6

如果你有一個元組列表,你可以試試下面的代碼來獲得你想要什麼。

import numpy as np 
import matplotlib.pyplot as plt 
popularity_data = [('Unknown', 10.0), 
    (u'Drew E.', 240.0), 
    (u'Anthony P.', 240.0), 
    (u'Thomas H.', 220.0), 
    (u'Ranae J.', 150.0), 
    (u'Robert T.', 120.0), 
    (u'Li Yan M.', 80.0), 
    (u'Raph D.', 210.0)] 

# sort in-place from highest to lowest 
popularity_data.sort(key=lambda x: x[1], reverse=True) 

# save the names and their respective scores separately 
# reverse the tuples to go from most frequent to least frequent 
people = zip(*popularity_data)[0] 
score = zip(*popularity_data)[1] 
x_pos = np.arange(len(people)) 

# calculate slope and intercept for the linear trend line 
slope, intercept = np.polyfit(x_pos, score, 1) 
trendline = intercept + (slope * x_pos) 

plt.plot(x_pos, trendline, color='red', linestyle='--')  
plt.bar(x_pos, score,align='center') 
plt.xticks(x_pos, people) 
plt.ylabel('Popularity Score') 
plt.show() 

這會給你類似下面的情節,雖然它沒有任何意義,當你不使用時間序列上繪製柱狀圖趨勢線。

Bar plot of popularity_data

參考文獻: