I wanted to know if there was an easier way I could put a linear regression line on a plotly subplot. The code I made below does not appear to be efficient and it makes it difficult to add annotations to the graph for the linear trendlines, which I want placed on the graph. Furthermore, it is hard to make axes and titles with this code.
I was wondering if there was a way I could create a go.Figure and somehow put it on the subplot. I have tried that, but plotly will only allow me to put the data from the figure on the subplot rather than the actual Figure, so I lose the title, axis, and trendline information. In addition, the trendline is hidden on the graphs because the scatterplot is overlaid on top of it. I tried changing how the data was displayed with data=(data[1],data[0]), but that did not work.
Basically, I want to know if there is a more efficient way of putting a trendline on the scatter plots than I pursued, so I can make it easier to set axes, set the graph size, create legends, etc, since it is difficult to work with what I coded .
sheets_dict=pd.ExcelFile('10.05.22_EMS172LabReport1.xlsx')
sheets_list=np.array(sheets_dict.sheet_names[2:])
fig=make_subplots(rows=7,cols=1)
i=0
for name in sheets_list:
df=sheets_dict.parse(name)
df.columns=df.columns.str.replace(' ','')
df=df.drop(df.index[0])
slope,y_int=np.polyfit(df.CURR1,df.VOLT1,1)
LR="Linear Fit: {:,.3e}x + {:,.3e}".format(slope,y_int)
rmse=np.sqrt(sum(slope*df.CURR1+y_int-df.VOLT1)**2)
df['Best Fit']=slope*df.CURR1+y_int
i+=1
fig.add_trace(
go.Scatter(name='Best Fit Line'+" ± {:,.3e}V".format(rmse),x=df['CURR1'],y=df['Best Fit'],
mode='lines',line_color='red',line_width=2),row=i, col=1)
fig.add_trace(
go.Scatter(name='Voltage',x=df['CURR1'],y=df['VOLT1'],mode='markers'),
row=i, col=1)
# fig.data = (fig.data[1],fig.data[0])
fig.show()