python - 如何在 Matplotlib 中限制水平线的时间范围范围

标签 python python-3.x pandas dataframe 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()

我当前的输出: Output

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

dff 输出:

                 Time  Price    Volume
0 2019-02-15 09:15:02  132.90   111.0
1 2019-02-15 09:15:03  134.15    78.0
2 2019-02-15 11:14:46  132.65    68.0
3 2019-02-15 11:27:24  131.95    73.0
4 2019-02-15 12:40:36  129.50   176.0
5 2019-02-15 13:42:52  129.90    75.0
6 2019-02-15 13:52:26  130.05    71.0
7 2019-02-15 13:52:40  129.70    99.0

我想要的输出: Desired

最佳答案

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()

函数plt.axhline有两个参数xminxmax。 而且它们只能接受 0 到 1 之间的 float 。所以上面有一个 normalize 函数。

关于python - 如何在 Matplotlib 中限制水平线的时间范围范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54709797/

相关文章:

python - 如何使用生产数据在 Django 中运行测试(只读)?

python - 如何在pyspark中获取连续的id

python - 如何将 pandas 中的列转换为一个日期时间列?

python - 使用 pandas 根据列删除整行

python - 当条件有效时,Pandas 将函数应用于列 - 更深层次的版本

python - Django 1.8 检查 View 中是否存在模板

python-3.x - 如何打开其中包含整数的文件/路径 - Python3

python - 搜索查询仅适用于数据框的第一行

python - 通过 map 向 DataFrame 添加 3 列

python - 计算Python中分配给某个值的变量数量