Matplotlib修复轴-日期过多

Beq*_*ani 2 python csv datetime numpy matplotlib

我有大量数据作为csv文件,其中包含过多的日期,因此在进行绘制时,x轴会全部写入它们,例如fe:from 2000-12-242017-12-24y轴。

我尝试使用一个集合,但是该集合需要排序,问题是当我对其进行排序时,来自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()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ans 6

您需要先将日期转换为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()   
Run Code Online (Sandbox Code Playgroud)

这只会给您几年: 年定位器

或者,如果您取消注释次要定位器/格式化程序,则会得到: 年月定位器

注意:

  1. 如果使用with块打开文件,则无需关闭文件。

  2. 该脚本假定您使用的是Python3.x。

  3. 要跳过标头,只需next()在遍历for循环中的行之前先阅读使用即可。