Plot csv file in matplotlib

2019-08-10 20:22发布

I imported csv file as a list in python:

csv file:

2012,3,22
2012,3,30
2012,4,4
2012,4,7
2012,3,22
2012,3,22
2012,3,27
2012,3,30
2012,3,30
2012,4,7

code:

import csv
with open('file.csv', 'rb') as f:
    reader = csv.reader(f)
    date_list = list(reader)

print date_list

the output is:

 [['2012', '3', '22'], ['2012', '3', '27'], ['2012', '3', '30'], ['2012', '3', '30'], ['2012', '4', '7']]

Now I want to plot it with matplotlib. my code is here but I do not know to apply my data into the code to generate the bar chart

I need just Year and month from the data. as you can see it in example

1条回答
爷、活的狠高调
2楼-- · 2019-08-10 20:45

To get your monthly counts into the format you need for the stacked bar chart from your previous question

You could convert and extract as follows:

import numpy as np
a = [['2012', '3', '22'], ['2012', '3', '27'], ['2012', '3', '30'], ['2012', '3', '30'], ['2012', '4', '7'], ['2011', '2', '12'], ['2011', '2', '14'], ['2011', '10', '10']]
# convert all date parts to integers
a = [[int(e) for e in d] for d in a]

years = set(d[0] for d in a)
minyear, maxyear = min(years), max(years)
nyears = maxyear - minyear + 1
nmonths = 12

monthly_counts = np.zeros((nyears,nmonths))
for year,month,_ in a:
    monthly_counts[year-minyear,month-1] += 1
查看更多
登录 后发表回答