猿问

如何在 Matplotlib 中限制具有时间范围范围的水平线

我的代码:


import matplotlib.pyplot as plt

import pandas as pd

import numpy as np


lot_size = 3750

min_vol = 60

path = 'C:\\Data\\ONGC19FEBFUT.txt'

df = pd.read_csv(path, sep=",")

df.columns = ['Date','Time','Price','volume']

df['Volume'] = np.where((df.volume/lot_size) < min_vol, 0, (df.volume/lot_size))

df["Time"] = pd.to_datetime(df['Time'])


df.plot(x="Time",y='Price', rot=0, color='g')


plt.title("Date: " + str(df['Date'].iloc[0]))


dff = df[df.Volume > min_vol].reset_index(drop=True)

dff = dff[['Time','Price','Volume']]

print(dff)


dict = dff.to_dict('index')

for x in range(0, len(dict)):

    plt.axhline(y=dict[x]['Price'],linewidth=1, color='blue')


plt.subplots_adjust(left=0.05, bottom=0.06, right=0.95, top=0.96, wspace=None, hspace=None)

plt.show()

我的当前输出: 

Dataframe dff给出了要在图表上绘制的价格值。我想分离要按 30 分钟持续时间绘制的价格值,即要在时间范围内绘制从 09:00 到 09:30 的价格值,要在此时间范围内绘制从 09:30 到 10:00 的价格值等等。我想限制每 30 分钟时间范围的水平价格线。



翻过高山走不出你
浏览 180回答 1
1回答

汪汪一只猫

import matplotlib.pyplot as pltimport pandas as pdimport numpy as npfrom datetime import datetimelot_size = 3750min_vol = 60path = 'ONGC19FEBFUT.txt'df = pd.read_csv(path, sep=",")df.columns = ['Date','Time','Price','volume']df['Volume'] = np.where((df.volume/lot_size) < min_vol, 0, (df.volume/lot_size))df["Time"] = pd.to_datetime(df['Time'])pic = df.plot(x="Time",y='Price', rot=0, color='g')pic.margins(0.0)plt.title("Date: " + str(df['Date'].iloc[0]))dff = df[df.Volume > min_vol].reset_index(drop=True)dff = dff[['Time','Price','Volume']]print(dff)dict = dff.to_dict('index')# get the 30-min interval in which x residesdef get_interval(x):&nbsp; &nbsp; y, m, d = x.year, x.month, x.day&nbsp; &nbsp; if x.minute < 30:&nbsp; &nbsp; &nbsp; &nbsp; hours = (x.hour, x.hour)&nbsp; &nbsp; &nbsp; &nbsp; minute = (0,30)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; hours = (x.hour, x.hour+1)&nbsp; &nbsp; &nbsp; &nbsp; minute = (30,0)&nbsp; &nbsp; return datetime(y, m, d, hours[0], minute[0], 0), datetime(y, m, d, hours[1], minute[1], 0)start = df["Time"][0]end = df["Time"][df["Time"].size-1]# get the position of x in x-axisdef normalize(x):&nbsp; &nbsp; return (x-start)/(end-start)for x in range(0, len(dict)):&nbsp; &nbsp; interval = get_interval(dict[x]["Time"])&nbsp; &nbsp; xmin, xmax = list(map(normalize, interval))&nbsp; &nbsp; plt.axhline(y=dict[x]['Price'], xmin=xmin, xmax=xmax, linewidth=1, color='blue')plt.subplots_adjust(left=0.05, bottom=0.06, right=0.95, top=0.96, wspace=None, hspace=None)plt.show()有两个参数xmin,并xmax用于功能plt.axhline。而且它们只能接受0到1之间的浮点数。所以normalize上面有一个函数。
随时随地看视频慕课网APP

相关分类

Python
我要回答