2017-09-16 33 views
0

我與編碼像這樣的數據集工作:使用Python把一個元組列表成柱狀圖/條形圖

[ 
    [ 
     (u'90000', 100318), 
     (u'21000', 58094), 
     (u'50000', 14695), 
     (u'250000', 8190), 
     (u'100000', 5718), 
     (u'40000', 4276) 
    ] 
] 

我想它transmogrify成柱狀圖/條形圖。

我一直在尋找XXX,迄今爲止我試圖像這樣:

fig, ax = plt.subplots() 
ax.yaxis.set_major_formatter(formatter) 
plt.bar(x, counts) 
plt.xticks(counts[0], counts[1]) 

plt.xticks(rotation=70) 
plt.show() 

然而,所產生的錯誤:

NameError: name 'formatter' is not defined 

用於產生數據結構的代碼看起來是這樣的:

with open('toy_two.json', 'rb') as inpt: 

    dict_hash_gas = list() 
    for line in inpt: 
     resource = json.loads(line) 
     dict_hash_gas.append({resource['first']:resource['second']}) 

# Count up the values 
counts = collections.Counter(v for d in dict_hash_gas for v in d.values()) 

counts = counts.most_common() 

# Apply a threshold 
threshold = 4275 
counts = [list(group) for val, group in itertools.groupby(counts, lambda x: x[1] > threshold) if val] 

print(counts) 

而且這樣的數據:

{"first":"A","second":"1","third":"2"} 
{"first":"B","second":"1","third":"2"} 
{"first":"C","second":"2","third":"2"} 
{"first":"D","second":"3","third":"2"} 
{"first":"E","second":"3","third":"2"} 
{"first":"F","second":"3","third":"2"} 
{"first":"G","second":"3","third":"2"} 
{"first":"H","second":"4","third":"2"} 
{"first":"I","second":"4","third":"2"} 
{"first":"J","second":"0","third":"2"} 
{"first":"K","second":"0","third":"2"} 
{"first":"L","second":"0","third":"2"} 
{"first":"M","second":"0","third":"2"} 
{"first":"N","second":"0","third":"2"} 

問題:

要清楚的問題是:如何使這個帖子開頭的數據,即

[ 
    [ 
     (u'90000', 100318), 
     (u'21000', 58094), 
     (u'50000', 14695), 
     (u'250000', 8190), 
     (u'100000', 5718), 
     (u'40000', 4276) 
    ] 
] 

爲直方圖?

x軸將是u'90000',u'21000',...,u'40000'

y軸將是100318,58094,...,4276

+0

什麼問題? – wwii

+0

問題是 - 如何將該數據呈現爲直方圖 –

+0

什麼是'plt'?和'無花果'和'斧頭'? – wwii

回答

2
data = [ 
    [ 
     (u'90000', 100318), 
     (u'21000', 58094), 
     (u'50000', 14695), 
     (u'250000', 8190), 
     (u'100000', 5718), 
     (u'40000', 4276) 
    ] 
] 

移調數據,以獲得x和y的值

#data = data[0] 
#x, y = zip(*data) 
x, y = zip(*data[0]) 

壓縮的y值,使他們適合在屏幕上

import math 
y = [int(math.log(n, 1.5)) for n in y] 

遍歷數據,並創建直方圖

for label, value in zip(x, y): 
    print('{:>10}: {}'.format(label, 'x'*value)) 


>>> 
    90000: xxxxxxxxxxxxxxxxxxxxxxxxxxxx 
    21000: xxxxxxxxxxxxxxxxxxxxxxxxxxx 
    50000: xxxxxxxxxxxxxxxxxxxxxxx 
    250000: xxxxxxxxxxxxxxxxxxxxxx 
    100000: xxxxxxxxxxxxxxxxxxxxx 
    40000: xxxxxxxxxxxxxxxxxxxx 
>>> 
+1

'x,y = zip(* data [0])'可能更好,因此您不會改變原始數據。 – Alexander

+0

所以 - 這是完全可怕的 - 和超級創意 - 但我更像是想,把它放在mat plot lib或類似的東西里,你知道嗎? –

+1

@ s.matthew.english - 我不知道:關於這個問題沒有任何問題。 – wwii