簡體   English   中英

在matplotlib中繪制CSV文件

[英]Plot csv file in matplotlib

我將csv文件作為python中的列表導入:

CSV文件:

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

碼:

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

print date_list

輸出為:

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

現在我想用matplotlib繪制它。 我的代碼在這里,但我不知道將我的數據應用到代碼中以生成條形圖

我只需要數據中的年份和月份。 如您在示例中看到的

要將月度計數轉換為上一個問題所需的堆積條形圖格式,

您可以按照以下步驟進行轉換和提取:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM