13

How would one plot a vertical line in plotly offline, using python? I want to add lines at x=20, x=40, and x=60, all in the same plot.

def graph_contracts(self):
    trace1 = go.Scatter(
        x=np.array(range(len(all_prices))),
        y=np.array(all_prices), mode='markers', marker=dict(size=10, color='rgba(152, 0, 0, .8)'))
    data = [trace1]
    layout = go.Layout(title='Market Contracts by Period',
                       xaxis=dict(title='Contract #',
                                  titlefont=dict(family='Courier New, monospace', size=18, color='#7f7f7f')),
                       yaxis=dict(title='Prices ($)',
                                  titlefont=dict(family='Courier New, monospace', size=18, color='#7f7f7f')))
    fig = go.Figure(data=data, layout=layout)
    py.offline.plot(fig)

Generated graph

4 Answers 4

18

You can add lines via shape in layout, e.g.

import plotly
plotly.offline.init_notebook_mode()
import random

x=[i for i in range(100)]
trace = plotly.graph_objs.Scatter(x=x,
                                  y=[random.random() for _ in x],
                                  mode='markers')
shapes = list()
for i in (20, 40, 60):
    shapes.append({'type': 'line',
                   'xref': 'x',
                   'yref': 'y',
                   'x0': i,
                   'y0': 0,
                   'x1': i,
                   'y1': 1})

layout = plotly.graph_objs.Layout(shapes=shapes)
fig = plotly.graph_objs.Figure(data=[trace],
                               layout=layout)
plotly.offline.plot(fig)

would give you

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

You could also use yref: 'paper which forces the coordinates to be relative to the grid and not relative your values.
7

A feature for vertical and horizontal lines is implemented with Plotly.py 4.12 (released 11/20). It works for plotly express and graph objects. See here: https://community.plotly.com/t/announcing-plotly-py-4-12-horizontal-and-vertical-lines-and-rectangles/46783

Simple example:

import plotly.express as px

df = px.data.stocks(indexed=True)
fig = px.line(df)
fig.add_vline(x='2018-09-24')
fig.show()

1 Comment

I noticed that if you try adding annotation_text to that add_vline there for a date axis, plotly will through an error: unsupported operand type(s) for +: 'int' and 'datetime.date'
6

This is my example. The most important instruction is this.

fig.add_trace(go.Scatter(x=[12, 12], y=[-300,300], mode="lines", name="SIGNAL"))

The most important attribute is MODE='LINES'.

Actually this example is about a segment with x=12

EXAMPLE

    import pandas as pd
    import plotly.graph_objects as go
    import matplotlib.pyplot as plt
    import numpy as np
    import plotly.tools as tls




    df1 = pd.read_csv('./jnjw_f8.csv')



    layout = go.Layout(
    xaxis = go.layout.XAxis(
        tickmode = 'linear',
        tick0 = 1,
        dtick = 3
    ),
    yaxis = go.layout.YAxis(
        tickmode = 'linear',
        tick0 = -100,
        dtick = 3
    ))

    fig = go.Figure(layout = layout)

    fig.add_trace(go.Scatter(x = df1['x'], y = 
    df1['y1'],name='JNJW_sqrt'))
    fig.add_trace(go.Scatter(x=[12, 12], y=[-300,300], 
    mode="lines", name="SIGNAL"))


    fig.show()

Look here too. how to plot a vertical line with plotly

Comments

3
fig.add_vline(x=2.5, line_width=3, line_dash="dash", line_color="green")

2 Comments

The community encourages adding explanations alongisde code, rather than purely code-based answers (see here).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.