来自不同DataFrame列的Python绘图线

问题描述 投票:0回答:1

例如,我在DataFrame中有来自三个股市交易的数据

df2 = pd.DataFrame(np.array([
    [10:00, 11:00, 12:00], 
    [10:03, 11:07, 12:09], 
    [67093, 67010, 66000], 
    [67095, 67012, 66010]]),
    columns=[
        'time_opened', 
        'time_closed', 
        'level_opened', 
        'level_closed'
    ]
)

我有一个图表,在x轴上有时间,在y轴上有水平(或股票价格)。我想画一条线/形状代表从每个time_opened / level_opened到time_closed / level_closed的每笔交易。即从670:00在10:00到67095在10:03

我正在尝试做这样的事情:

    fig.add_shape(
        dict(
            type='line',
            x0=positions['time_opened'],
            y0=positions['level_opened'],
            x1=positions['time_closed'],
            y1=positions['level_closed'],
            line=dict(color='Black', width=3),
        ),
    )
    fig.update_shapes(xaxis='x1')

任何想法我在做什么错吗?

python dataframe plotly
1个回答
0
投票
import plotly.graph_objects as go
import pandas as pd

df = pd.DataFrame({'time_opened': ['10:00', '11:00', '12:00'],
                   'time_closed': ['10:03', '11:07', '12:09'],
                   'level_opened': [67093, 67010, 66000],
                   'level_closed': [67095, 67012, 66010]})

df['time_opened'] = pd.to_datetime(df['time_opened'])
df['time_closed'] = pd.to_datetime(df['time_closed'])

layout = dict(xaxis=dict(range=[df['time_opened'].min() - pd.Timedelta('30M'),
                                df['time_closed'].max() + pd.Timedelta('30M')],
                         type='date',
                         tickformat='%H:%M'))

data = []

for i in range(df.shape[0]):

    data.append(go.Scatter(x=[df['time_opened'][i], df['time_closed'][i]],
                           y=[df['level_opened'][i], df['level_closed'][i]],
                           name='trade ' + str(i + 1)))

fig = go.Figure(data=data, layout=layout)

fig.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.