![](/img/trans.png)
[英]Can I set default values with matplotlib and pandas for each x tick?
[英]How can I adjust the bounds of the x tick values that are automatically chosen by matplotlib?
我有一张图表,显示了一天中每五分钟一次的股票收盘价。 x 轴显示时间,x 值的范围是从 9:30 到 4:00 (16:00)。 问题是 x 轴 go 从 9:37 到 16:07 的自动边界,我真的只想要从 9:30 到 16:00。
我目前正在运行的代码是这样的:
stk = yf.Ticker(ticker)
his = stk.history(interval="5m", start=start, end=end).values.tolist() #open - high - low - close - volume
x = []
y = []
count = 0
five_minutes = datetime.timedelta(minutes = 5)
for bar in his:
x.append((start + five_minutes * count))#.strftime("%H:%M"))
count = count + 1
y.append(bar[3])
plt.clf()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
plt.gca().xaxis.set_major_locator(mdates.MinuteLocator(interval=30))
plt.plot(x, y)
plt.gcf().autofmt_xdate()
plt.show()
它产生这个 plot (目前是一个链接,因为我在一个新的用户帐户上):
我以为我应该使用axis.set_data_interval function提供,所以我通过提供代表9:30和16:00的日期时间对象作为最小值和最大值来做到这一点。 这给了我错误:
TypeError: 'float' 和 'datetime.datetime' 的实例之间不支持'<'
是否有另一种方法可以让我调整第一个 xtick 并让它自动填充 rest?
这个问题可以通过调整你使用mdates
刻度定位器的方式来解决。 这是一个基于 r-beginners 共享的示例,以使其具有可比性。 请注意,为方便起见,我使用pandas 绘制 function 。 需要x_compat=True
参数才能与mdates
一起使用:
import pandas as pd # 1.1.3
import yfinance as yf # 0.1.54
import matplotlib.dates as mdates # 3.3.2
# Import data
ticker = 'AAPL'
stk = yf.Ticker(ticker)
his = stk.history(period='1D', interval='5m')
# Create pandas plot with appropriately formatted x-axis ticks
ax = his.plot(y='Close', x_compat=True, figsize=(10,5))
ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0, 30]))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M', tz=his.index.tz))
ax.legend(frameon=False)
ax.figure.autofmt_xdate(rotation=0, ha='center')
样本数据是通过从 Yahoo Finance 获取 Apple 的股票价格创建的。 所需的五分钟间隔标签是通过使用日期 function 获取以五分钟间隔获取开始和结束时间的字符串列表。 在此基础上,将 x 轴绘制为五分钟间隔数和收盘价的图表,通过切片将 x 轴设置为任意间隔。
import yfinance as yf
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np
ticker = 'AAPL'
stk = yf.Ticker(ticker)
his = stk.history(period='1D',interval="5m")
his.reset_index(inplace=True)
time_rng = pd.date_range('09:30','15:55', freq='5min')
labels = ['{:02}:{:02}'.format(t.hour,t.minute) for t in time_rng]
fig, ax = plt.subplots()
x = np.arange(len(his))
y = his.Close
ax.plot(x,y)
ax.set_xticks(x[::3])
ax.set_xticklabels(labels[::3], rotation=45)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.