8

I am using plotly (the offline version) within an IPython notebook and I like it a lot. However I couldn't find a way to plot a vertical line or a vertical band.

The equivalents in matplotlib are:

import matplotlib.plyplot as plt
plt.axvline(x=0)
plt.axvspan(xmin=0, xmax=1)

thanks in advance

JavaNewbie
  • 241
  • 3
  • 6

3 Answers3

6

You can add shapes to your plotly layout. Shapes can include lines or rectangles. They can also be made unbounded by drawing them relative to the plotting area rather than a particular axis. Have a look through the examples in the plotly shapes docs.

layout = {
        'title': "My Chart",
        'shapes': [
            {  # Unbounded line at x = 4
                'type': 'line',
                # x-reference is assigned to the x-values
                'xref': 'x',
                # y-reference is assigned to the plot paper [0,1]
                'yref': 'paper',
                'x0': 4,
                'y0': 0,
                'x1': 4,
                'y1': 1,
                'line': {
                    'color': 'rgb(55, 128, 191)',
                    'width': 3,
                }
            },
            {  # Unbounded span at 6 <= x <= 8
                'type': 'rect',
                # x-reference is assigned to the x-values
                'xref': 'x',
                # y-reference is assigned to the plot paper [0,1]
                'yref': 'paper',
                'x0': 6,
                'y0': 0,
                'x1': 8,
                'y1': 1,
                'fillcolor': '#d3d3d3',
                'opacity': 0.2,
                'line': {
                    'width': 0,
                }
            }
        ],
    }
Kieran
  • 771
  • 7
  • 14
0

I'm just starting out with plotly myself, and so far I haven't found a good way to do this. But if you only need one horizontal or vertical line, the code below seems to be a workable hack, The idea is to use the default grid, but only plot a single grid line at the desired height. Include the following in your layout dict, and it will plot a horizontal line at yline.

  yaxis=dict(
         zeroline=False,
         autotick=False,
         showgrid=True,
         tick0=yline,
         dtick=<something very large, so that next lines are out of range>
  )
Peter
  • 567
  • 3
  • 10
0

I would use the 'shapes' option in the layout. For example, to get a vertical line at x = 6:

layout = {'title' : 'example',
          'shapes' : [{'type' : 'line', 'x0' : 6, 
                      'x1' : 6, 'y0' : 0, 'y1' : 10, 
                       'width' : 1}]}

You could change the width parameter to plot a vertical band.

Rytchbass
  • 406
  • 1
  • 5
  • 11