为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

翻过高山走不出你 2021-11-09 20:00:53
我的代码:import matplotlib.pyplot as pltimport pandas as pdimport numpy as nplot_size = 3750min_vol = 60path = '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 分钟时间范围的水平价格线。
查看完整描述

1 回答

?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

import matplotlib.pyplot as plt

import pandas as pd

import numpy as np

from datetime import datetime


lot_size = 3750

min_vol = 60

path = '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 resides

def get_interval(x):

    y, m, d = x.year, x.month, x.day

    if x.minute < 30:

        hours = (x.hour, x.hour)

        minute = (0,30)

    else:

        hours = (x.hour, x.hour+1)

        minute = (30,0)

    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-axis

def normalize(x):

    return (x-start)/(end-start)


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

    interval = get_interval(dict[x]["Time"])

    xmin, xmax = list(map(normalize, interval))

    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上面有一个函数。


查看完整回答
反对 回复 2021-11-09
  • 1 回答
  • 0 关注
  • 179 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信