akhil
akhil

Reputation: 19

Draw line in plotly between 2 points?

Here is the code:

import plotly.graph_objects as go
import pandas as pd
from datetime import datetime

# build complete timepline from start date to end date
dt_all = pd.date_range(start=raw_bn1['Date'].iloc[0],end=raw_bn1['Date'].iloc[-1])

# retrieve the dates that ARE in the original datset
dt_obs = [d.strftime("%Y-%m-%d") for d in pd.to_datetime(raw_bn1['Date'])]

# define dates with missing values
dt_breaks = [d for d in dt_all.strftime("%Y-%m-%d").tolist() if not d in dt_obs]

fig = go.Figure(data=[go.Candlestick(x=raw_bn1['Date'],
                open=raw_bn1['Open'],
                high=raw_bn1['High'],
                low=raw_bn1['Low'],
                close=raw_bn1['Close'])])
fig.update_layout(xaxis_rangeslider_visible=False)
fig.update_xaxes(rangebreaks=[dict(values=dt_breaks)])
fig.show()

I am getting a candlestick chart by this. Now I would like to join 2 dates ( for ex- 1st Dec 2020 and 13th August 2021) 'High' with a straight line. How to do it ?

Upvotes: 0

Views: 2890

Answers (1)

r-beginners
r-beginners

Reputation: 35240

Line segments were added using candlestick data from the official reference. With the addition of a line chart, set the x-axis to the start date, the end date, and the y-axis to the price on the start date and the price on the end date in a list.

import plotly.graph_objects as go
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

fig = go.Figure(data=[go.Candlestick(x=df['Date'],
                open=df['AAPL.Open'], high=df['AAPL.High'],
                low=df['AAPL.Low'], close=df['AAPL.Close'])
                     ])

fig.add_trace(go.Scatter(x=['2016-11-02','2017-01-26'], y=[111,125], mode='lines', name='trend line', line=dict(color='blue')))
fig.update_layout(xaxis_rangeslider_visible=False)
fig.show()

enter image description here

Upvotes: 1

Related Questions