[英]How to create a bar graph from csv with dates as the x-axis
I want to generate a bar graph from from a csv file my data looks like this: 我想从csv文件生成一个条形图,我的数据如下所示:
06/14/12 SMB 12104560 8096373.6 1.5 1.08
06/15/12 SMB 10328540 8217192.68 1.26 1.24
06/18/12 SMB 5495294 8232792.78 0.67 0.85
I want the first column to be the x-axis and the last column to be the y-axis, Also if possible I just want to use the last 5 rows of data. 我希望第一列是x轴,最后一列是y轴,如果可能,我只想使用最后5行数据。 This is what I have tried so far but Thanks
这是我到目前为止所尝试的但是谢谢
Edit New code: 编辑新代码:
data = numpy.loadtxt(StringIO(etf + '.csv' ,dtype= [("date", "S8"), ("value", "f8")]) , usecols=(0,-1))
x = numpy.arange(len(data))
pl1.bar(x,data["value"], width = 0.8)
p1.xticks(x+.4, data["date"])
p1.show()
new error: TypeError: __init__() got an unexpected keyword argument 'dtype'
新错误:
TypeError: __init__() got an unexpected keyword argument 'dtype'
import numpy as np
from StringIO import StringIO
import pylab as pl
datastr = """06/14/12 SMB 12104560 8096373.6 1.5 1.08
06/15/12 SMB 10328540 8217192.68 1.26 1.24
06/18/12 SMB 5495294 8232792.78 0.67 0.85"""
data = np.loadtxt(StringIO(datastr),
dtype=np.dtype([("date", "S8"), ("value", "f8")]),
usecols=(0,-1))
x = np.arange(len(data))
pl.bar(x, data["value"], width=0.8)
pl.xticks(x+0.4, data["date"])
pl.show()
For any plotting purposes I would recommend using matplotlib. 对于任何绘图目的,我建议使用matplotlib。
There is an easy example to plot a bar chart - very similar to what you are using but sometimes it helps to start over from scratch. 有一个简单的例子来绘制条形图 - 非常类似于您正在使用的条形图,但有时它有助于从头开始。
Also, where exactly are you getting the TypeError? 另外,你究竟在哪里获得TypeError?
Regarding the last 5 elements, you can always use the python's list splicing, eg list[-5:]
关于最后5个元素,你总是可以使用python的列表拼接,例如
list[-5:]
I have no idea about matplotlib but this could be the problem: 我不知道matplotlib,但这可能是问题:
date.append((col[0])) # <- appending a string
maybe you should try using 也许你应该尝试使用
ax.set_xticklabels(...)
to get the string labels as it looks the 'date' list should not be a string. 获取字符串标签,因为它看起来'日期'列表不应该是一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.