使用Matplotlib跳过Python中的某些值

使用Matplotlib跳过Python中的某些值,python,matplotlib,axis-labels,Python,Matplotlib,Axis Labels,我目前正在使用Alpha Vantage API制作日内股票图表。数据框包含从4:00到20:00的值。但是,在我的matplotlib.pyplot图表中,x轴还包括夜间20:00到4:00之间的值。我不想这样,因为它打乱了美学和音量子地块 问:有没有办法跳过实际数据帧中不存在的x轴值(从20:00到04:00的值) 代码到目前为止。我相信到目前为止一切都是对的: import pandas as pd import matplotlib.pyplot as plt from alpha_

我目前正在使用Alpha Vantage API制作日内股票图表。数据框包含从4:00到20:00的值。但是,在我的matplotlib.pyplot图表中,x轴还包括夜间20:00到4:00之间的值。我不想这样,因为它打乱了美学和音量子地块

问:有没有办法跳过实际数据帧中不存在的x轴值(从20:00到04:00的值)

代码到目前为止。我相信到目前为止一切都是对的:

import pandas as pd
import matplotlib.pyplot as plt
from alpha_vantage.timeseries import TimeSeries
import time
import datetime as dt
from datetime import timedelta as td 
from dateutil.relativedelta import relativedelta

#Accessing and Preparing API
ts = TimeSeries(key=api_key, output_format='pandas')

ticker_input = "TSLA"
interval_input = "15min"
df, meta_data = ts.get_intraday(symbol = ticker_input, interval = interval_input, outputsize = 'full')
slice_date = 16*4*5
df = df[0:slice_date]
df = df.iloc[::-1]
df["100ma"] = df["4. close"].rolling(window = 50, min_periods = 0).mean()
df["Close"] = df["4. close"]
df["Date"] = df.index

#Plotting all as 2 different subplots
ax1 = plt.subplot2grid((7,1), (0,0), rowspan = 5, colspan = 1)
ax1.plot(df["Date"], df['Close'])
ax1.plot(df["Date"], df["100ma"], linewidth = 0.5)
plt.xticks(rotation=45)
ax2 = plt.subplot2grid((6,1), (5,0), rowspan = 2, colspan = 2, sharex = ax1)
ax2.bar(df["Date"], df["5. volume"])
ax2.axes.xaxis.set_visible(False)
plt.tight_layout()
plt.show()

如果有人能帮忙,那就太好了。我还是一个完全的初学者,两周前才开始学习Python。

我们从同一个地方获得了数据,尽管数据采集方法不同。在将其提取为15个单元后,我通过排除晚上8点之后和下午4点之前的数据创建了一个图表。我创建代码的目的是理解您的跳过将打开暂停。设置NaN后,将跳过要跳过的内容

import datetime
import pandas as pd
import numpy as np
import pandas_datareader.data as web
import mplfinance as mpf
# import matplotlib.pyplot as plt

with open('./alpha_vantage_api_key.txt') as f:
    api_key = f.read()

now_ = datetime.datetime.today()

start = datetime.datetime(2019, 1, 1)
end = datetime.datetime(now_.year, now_.month, now_.day - 1)

symbol = 'TSLA'
df = web.DataReader(symbol, 'av-intraday', start, end, api_key=api_key)

df.columns = ['Open', 'High', 'Low', 'Close', 'Volume']
df.index = pd.to_datetime(df.index)
df["100ma"] = df["Close"].rolling(window = 50, min_periods = 0).mean()
df["Date"] = df.index
df_15 = df.asfreq('15min')
df_15 = df_15[(df_15.index.hour >= 4)&(df_15.index.hour <= 20) ]

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,4.5),dpi=144)

#Plotting all as 2 different subplots
ax1 = plt.subplot2grid((7,1), (0,0), rowspan = 5, colspan = 1)
ax1.plot(df_15["Date"], df_15['Close'])
ax1.plot(df_15["Date"], df_15["100ma"], linewidth = 0.5)
plt.xticks(rotation=20)

ax2 = plt.subplot2grid((6,1), (5,0), rowspan = 2, colspan = 2, sharex = ax1)
ax2.bar(df_15["Date"], df_15["Volume"])
ax2.axes.xaxis.set_visible(False)
# plt.tight_layout()
plt.show()
导入日期时间
作为pd进口熊猫
将numpy作为np导入
以web形式导入datareader.data
输入强积金
#将matplotlib.pyplot作为plt导入
将open('./alpha_vantage_api_key.txt')作为f:
api_key=f.read()
now=datetime.datetime.today()
start=datetime.datetime(2019,1,1)
end=datetime.datetime(现在是年,现在是月,现在是天-1)
符号='TSLA'
df=web.DataReader(符号“av日内”,开始,结束,api_键=api_键)
df.columns=['Open'、'High'、'Low'、'Close'、'Volume']
df.index=pd.to_datetime(df.index)
df[“100ma”]=df[“关闭”]。滚动(窗口=50,最小周期=0)。平均值()
df[“日期”]=df.index
df_15=df.asfreq('15min')

df_15=df_15[(df_15.index.hour>=4)和(df_15.index.hour我使用matplotlib.ticker.formatter修复了它

我首先创建了一个类,并使用:

class MyFormatter(Formatter):
    def __init__(self, dates, fmt='%Y-%m-%d %H:%M'):
        self.dates = dates
        self.fmt = fmt

    def __call__(self, x, pos=0):
        'Return the label for time x at position pos'
        ind = int(np.round(x))
    if ind >= len(self.dates) or ind < 0:
        return ''
    return self.dates[ind].strftime(self.fmt)

formatter = MyFormatter(df.index)
ax1 = plt.subplot2grid((7,1), (0,0), rowspan = 5, colspan = 1)
ax1.xaxis.set_major_formatter(formatter)
ax1.plot(np.arange(len(df)), df["Close"])
ax1.plot(np.arange(len(df)), df["100ma"], linewidth = 0.5)
ax1.xticks(rotation=45)
ax1.axis([xmin,xmax,ymin,ymax])
ax2 = plt.subplot2grid((6,1), (5,0), rowspan = 2, colspan = 2, sharex = ax1)
ax2.bar(np.arange(len(df)), df["5. volume"])

plt.show()
类MyFormatter(格式化程序):
定义初始化(self,dates,fmt='%Y-%m-%d%H:%m'):
self.dates=日期
self.fmt=fmt
定义调用(self,x,pos=0):
'返回位置处时间x的标签'
ind=整数(np.四舍五入(x))
如果ind>=len(自日期)或ind<0:
返回“”
返回self.dates[ind].strftime(self.fmt)
格式化程序=MyFormatter(df.index)
ax1=plt.subplot2grid((7,1)、(0,0),rowspan=5,colspan=1)
ax1.xaxis.set\u major\u格式化程序(格式化程序)
ax1.绘图(np.arange(len(df)),df[“Close”])
ax1.绘图(np.arange(len(df)),df[“100ma”],线宽=0.5)
ax1.xticks(旋转=45)
ax1.轴([xmin,xmax,ymin,ymax])
ax2=plt.subplot2grid((6,1)、(5,0),行span=2,列span=2,共享x=ax1)
ax2.bar(np.arange(len(df)),df[“5.volume”])
plt.show()
这给了我一个比以前更平滑的图,也是r初学者推荐的图。


我唯一的问题是,如果我放大x轴,它不会真正改变。它总是有年、月、日期、小时和分钟。显然,当我进一步放大时,我只想要小时和分钟。我还没有弄清楚如何做到这一点。

也许这有帮助:问题是相似的,但这个问题也没有任何答案。还有Matplotib站点并没有真正的帮助,因为它限制了一个精确的y值。每当它达到20:00时,我想跳过它,无论是18-08-2020 20:00还是25-12-2025 20:00。因此,该解决方案并不真正适用于我这里:也可能在这里: