Search code examples
pythongraphcenterscatter-plotplotly

Centering line scatterplot in plotly


I am creating a line scatter plot using plotly python API. There are old and new data plotted in y-axis with the date in the x-axis.I would like to center the graph such that one part of the graph is old data and another half of the graph is new data. How can this be done in plotly?In the attached image, the blue one represents old and orange represents new data. How old and new can be centered such that one part of the graph is old data and another half of the graph is new data? Plotly_Line_Scatterplot


Solution

  • Building on the manual axes example from the Plotly documentation:

    import plotly.plotly as py
    import plotly.graph_objs as go
    
    xold=[5, 6, 7, 8]
    yold=[3, 2, 1, 0]
    xnew=[10, 11, 12, 13, 14, 15, 16, 17, 18]
    ynew=[0, 1, 2, 3, 4, 5, 6, 7, 8]
    
    oldData = go.Scatter(xold, yold)
    newData = go.Scatter(xnew, ynew)
    data = [oldData, newData]
    lenOld = max(xold) - min(xold)
    lenNew = max(xnew) - min(xnew)
    lenX = 2*max(lenOld,lenNew)
    layout = go.Layout(
        xaxis=dict(
            range=[min(xnew)-lenX/2, min(xnew)+lenX/2]
        )
    )
    fig = go.Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename='axes-range-manual')
    

    For simplicity I have used integers as x-values rather than using dates but the same principle will apply.

    Please note, I don't have plotly installed at present so I haven't tested this code.