如何使用输入* .txt文件绘制一个非常简单的条形图(Python,Matplotlib)? [英] How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?
问题描述
我使用Python 2.7和matplotlib.我有一个* .txt数据文件:
I use Python 2.7 and matplotlib. I have a *.txt data file :
0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014
文件的第一列(数字)应在条形图中的Y轴上,文件的第二列(日期)应在直方图中的OX轴上.我只知道如何读取文件:
first column of my file (numbers) should be on axis Y in my bar chart, and the second column from my file (dates) should be on axis OX in my histogram. I only know how to read the file:
OX = []
OY = []
try :
with open('data.txt', 'r') as openedFile :
for line in openedFile :
tab = line.split()
OY.append(int(tab[0]))
OX.append(str(tab[1]))
except IOError :
print("IOError!")
我确实阅读了matplotlib文档,但仍然无济于事.我还想将读取的日期添加到条形图中,以使其看起来像
I did read a matplotlib docs but it still doesn't help me. I would also like to add dates I read to my bar chart, to make it look like
有人可以帮我吗?
推荐答案
您正在谈论的是直方图,但这没有任何意义.直方图和条形图是不同的东西.例如,直方图将是代表每年值总和的条形图.在这里,您似乎只是在追求酒吧.
You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.
这是您数据中的一个完整示例,其中显示了每个日期每个必需值的条形:
Here is a complete example from your data that shows a bar of for each required value at each date:
import pylab as pl
import datetime
data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""
values = []
dates = []
for line in data.split("\n"):
x, y = line.split()
values.append(int(x))
dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())
fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()
您需要使用strptime
解析日期,并将x轴设置为使用日期(如此答案中所述).
You need to parse the date with strptime
and set the x-axis to use dates (as described in this answer).
如果您不希望X轴显示线性时间刻度,而只希望带有标签的条形,则可以执行以下操作:
If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:
fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)
在注释之后,对于所有刻度,并使其居中,将范围传递到set_ticks
(并将其移动一半条形宽度):
Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks
(and move them by half the bar width):
fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)
这篇关于如何使用输入* .txt文件绘制一个非常简单的条形图(Python,Matplotlib)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!