Single axis scatter plot + linear regression line

Hi, I use the following python code to plot a scatter plot with a linear regression line.

def scatterPlotWithLr(x,y, x_name, y_name, showlegend=False):
    mask = ~np.isnan(x) & ~np.isnan(y)
    slope, intercept, r_value, p_value, std_err = \
        sc.stats.linregress(x[mask],y[mask])
    line = slope*x+intercept
    pt_trace1 = go.Scatter(
        x=x,
        y=y,
        mode='markers',
        marker=go.Marker(color='#b71c1c'),
        name='Scatter Points'
    )
    pt_trace2 = go.Scatter(
        x=x,
        y=line,
        mode='lines',
        marker=go.Marker(color='#303f9f'),
        name='Linear Regression'
    )
    pt_annotation = go.Annotation(
        x=0.02,
        y=0.2,
        text='$R^2 = %s,\\S = %sR + %s$' %(round(r_value,2),
                                           round(slope,2),
                                           round(intercept,2)),
        showarrow=True,
        font=go.Font(size=16)
    )
    pt_layout = go.Layout(
        title='$R^2 = %s,\\S = %sR + %s$' %(round(r_value,2),
                                           round(slope,2),
                                           round(intercept,2)),
        xaxis=dict(
            title=x_name
        ),
        yaxis=dict(
            title=y_name
        ),
        annotations=[pt_annotation],
        showlegend=showlegend
    )
    pt_data = [pt_trace1, pt_trace2]
    pt_fig = go.Figure(data=pt_data, layout=pt_layout)
    return pt_fig

However the code creates two y-axis. any advise on how to just show one y-axis for both the line and the scatter plot?

@dfernan I ran your code with these data:

x=np.array([1,2,3.1, 6.7, 1.2])
y=np.array([0.7, 1.15, 2.54, 4.1, 2.2])

fig=scatterPlotWithLr(x,y, 'x', 'y')

but the plot does not display two y-axes.plot-forum

1 Like

itโ€™s very odd, it does not always happenโ€ฆ maybe itโ€™s because I am putting the plot in a grid?

This is what I see in my case which is two axis and a line that clearly doesnโ€™t even fit into the scatter plot due to the dual axis problem:

image

@dfernan What do you mean by putting the plot in a grid? Did you paste here the same code you used for the posted plot?

1 Like

@empet I fixed the issue thanks to you, no I did not put all the code.

By using a grid I meant I was using subplots and then adding an extra axis on the wrong subplot, that was causing the issue. Itโ€™s fixed now, thanks so much!

1 Like