如何调整 matplotlib 自动选择的 x 刻度值的边界?

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 轴的自动边界从 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()

它会生成这个图(目前是 link 因为我使用的是新用户帐户):

我认为我应该使用 axis.set_data_interval 函数提供,所以我通过提供表示 9:30 和 16:00 作为最小值和最大值的日期时间对象来实现。这给了我错误:

TypeError:'float' 和 'datetime.datetime'

实例之间不支持“<”

有没有其他方法可以让我调整第一个 xtick 并仍然自动填充其余部分?

示例数据是通过从雅虎财经获取 Apple 的股票价格创建的。所需的五分钟间隔标签是使用日期函数以五分钟间隔获取开始和结束时间而获得的字符串列表。 以此为基础绘制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()

可以通过调整 mdates 刻度定位器的使用方式来解决此问题。这是一个基于 r-beginners 共享的示例,以使其具有可比性。请注意,为方便起见,我使用 pandas plotting 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')