Deshwal
Deshwal

Reputation: 4152

Plotly: How to plot Horizontal line Between "2 Points" where points on x axis are Months

Is there a way to control the starting and ending points of horizontal and vertical lines in plotly?

import plotly.graph_objects as go
        
fig = go.Figure(data=go.Scatter())
fig.add_vline(x=1, line_width=2, line_dash="dash", line_color="green")
fig.add_hline(y=2, line_width=2, line_dash="dash", line_color="red")
fig.show()

Code above will plot lines but on whole screen

I want to do something like:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize = (10,7))

ax.hlines(y=2, xmin='July', xmax='Aug', linewidth=2, color='red', linestyles = 'dotted')
ax.axvline(x = 1,color = 'green', linestyle = 'dotted', linewidth = 2)

Upvotes: 2

Views: 5844

Answers (1)

Derek O
Derek O

Reputation: 19545

From the documentation, add_vline will span the entire y-axis of the plot, and add_hline will span the entire x-axis of the plot.

You can instead use the add_shape method for figures from Plotly Shapes and add a line segment by specifying the start and end coordinates using the arguments x0,x1,y0,y1.

EDIT: if you have datetimes on your x-axis, you can pass datetimes to the x-coordinate arguments

import plotly.express as px
import pandas as pd

df = px.data.stocks()

vertical_date_time         = pd.to_datetime("2018-07-01")
horizontal_date_time_start = pd.to_datetime("2018-04-01")
horizontal_date_time_end   = pd.to_datetime("2018-10-01")
    
fig = px.line(
    df, x='date', y="GOOG"
).add_shape(
    type="line", line_width=2, line_dash="dash", line_color="green", 
    x0=vertical_date_time, y0=0.9, 
    x1=vertical_date_time, y1=1.2
).add_shape(
    type="line",line_width=2, line_dash="dash", line_color="red",
    x0=horizontal_date_time_start, y0=1.05, 
    x1=horizontal_date_time_end, y1=1.05
)
    
fig.show()

enter image description here

Upvotes: 7

Related Questions