2013-04-23 77 views
-1

我們有一個文本文件中的數據如下條形圖:如何創建使用Python中matplotlib .txt文件數據

正面:20

負:10

中性:30

正面,負面,中性是標籤,20,10,30是計數。我的要求是爲上述數據繪製條形圖。 X軸應該是標籤,而Y軸應該是計數。 那麼你能告訴我如何在python中使用matplotlib來做到這一點。

我曾嘗試這個代碼,但收到的一些錯誤

f=open('/var/www/html/form/tweetcount.txt','r') 

line = (f.next() for i in range(4)) 
pieces = (lin.split(':') for lin in line) 

labels,values = zip(*pieces) 

N=len(values) 

ind = arange(N) 

plt.bar(ind,labels) 
+0

[你有什麼嘗試?](http://whathaveyoutried.com)這個問題有兩個部分:閱讀文本文件和製作條形圖。後者通過調用'plt.bar'然後設置標籤完成。 – Dougal 2013-04-23 05:04:55

+0

修改這個例子,以適應您的要求http://matplotlib.org/examples/pylab_examples/custom_ticker1.html – wim 2013-04-23 05:06:35

+0

我已經編輯我的文章的代碼。 – 2013-04-23 05:36:30

回答

1

我覺得你的問題是,你想要繪製錯誤的價值觀。

此代碼應該做你想要什麼:

import matplotlib.pyplot as plt 
import numpy as np 

# Collect the data from the file, ignore empty lines 
with open('data.txt') as f: 
    lines = [line.strip().split(': ') for line in f if len(line) > 1] 

labels, y = zip(*lines) 

# Generate indexes 
ind = np.arange(len(labels)) 

# Convert the y values from str to int 
y = map(int, y) 

plt.figure() 
plt.bar(ind, y, align='center') 
plt.xticks(ind, labels) 
plt.show() 

你可以看到最後的結果here