2013-04-23 73 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