我有大数据作为 csv 文件,其中有太多日期,所以当我绘制它时,x 轴写入所有这些,如 f.e :从 2000-12-24
到 2017 -12-24
还有 y 轴。
我曾尝试使用一个集合,但该集合需要排序,问题是当我对它排序时,来自 Y 的数据不适用于任何已排序的日期。
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 = []
openp = []
high = []
low = []
close = []
adjclose = []
volume = []
text = u.request.urlopen(stock_price_url).read().decode()
with open('nw.csv', 'w') as fw:
fw.write(text)
fw.close()
with open('nw.csv', 'r') as csvf:
f = csv.reader(csvf, delimiter=',')
for row in f:
if 'Date' not in row:
date.append(row[0])
openp.append(row[1])
high.append(row[2])
low.append(row[3])
close.append(row[4])
adjclose.append(row[5])
volume.append(row[6])
dateset = set([])
for z in date:
dateset.add(z[:4])
highset = []
for z in high:
highset.append(z[:3])
plt.plot(set(dateset), set(highset), linewidth=0.5)
plt.show()
最佳答案
您需要先将日期转换为 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
block 打开文件,则无需关闭文件。该脚本假定您使用的是 Python 3.x。
要跳过标题,只需在遍历 for 循环中的行之前使用
next()
读取它。
关于python - Matplotlib 修复轴 - 日期太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48090043/