简体   繁体   中英

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:

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. 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'

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.

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?

Regarding the last 5 elements, you can always use the python's list splicing, eg list[-5:]

I have no idea about matplotlib but this could be the problem:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM