我有大数据作为csv文件,它有太多日期,因此当我绘制它时,x轴会写出所有这些数据,例如fe:从notifyDataSetChanged
到2000-12-24
以及y轴。< / p>
我试图使用一个集合,但该集合需要排序,问题是当我对它进行排序时,Y的数据对于任何已排序的日期都不是。
2017-12-24
答案 0 :(得分:4)
您需要先将日期转换为Python datetime
对象。然后可以将其转换为matplotlib编号。有了这个,你可以告诉matplotlib根据年或月的变化添加滴答:
from datetime import datetime
import matplotlib
import matplotlib.pyplot as plt
import urllib as u
import numpy as np
import csv
stock_price_url = 'https://pythonprogramming.net/yahoo_finance_replacement'
date = []
high = []
text = u.request.urlopen(stock_price_url).read().decode()
with open('nw.csv', 'w') as f_nw:
f_nw.write(text)
with open('nw.csv', 'r', newline='') as f_nw:
csv_nw = csv.reader(f_nw)
header = next(csv_nw)
for row in csv_nw:
date.append(matplotlib.dates.date2num(datetime.strptime(row[0], '%Y-%m-%d')))
high.append(row[2])
ax = plt.gca()
#ax.xaxis.set_minor_locator(matplotlib.dates.MonthLocator([1, 7]))
#ax.xaxis.set_minor_formatter(matplotlib.dates.DateFormatter('%b'))
ax.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y'))
#ax.tick_params(pad=20)
plt.plot(date, high, linewidth=0.5)
plt.show()
注意:
如果您使用with
块打开文件,则无需关闭文件。
该脚本假定您使用的是Python 3.x。
要跳过标题,只需在迭代for循环中的行之前使用next()
读取它。