<bdo id='g5CH1'></bdo><ul id='g5CH1'></ul>
      <i id='g5CH1'><tr id='g5CH1'><dt id='g5CH1'><q id='g5CH1'><span id='g5CH1'><b id='g5CH1'><form id='g5CH1'><ins id='g5CH1'></ins><ul id='g5CH1'></ul><sub id='g5CH1'></sub></form><legend id='g5CH1'></legend><bdo id='g5CH1'><pre id='g5CH1'><center id='g5CH1'></center></pre></bdo></b><th id='g5CH1'></th></span></q></dt></tr></i><div id='g5CH1'><tfoot id='g5CH1'></tfoot><dl id='g5CH1'><fieldset id='g5CH1'></fieldset></dl></div>
    1. <legend id='g5CH1'><style id='g5CH1'><dir id='g5CH1'><q id='g5CH1'></q></dir></style></legend><tfoot id='g5CH1'></tfoot>
    2. <small id='g5CH1'></small><noframes id='g5CH1'>

        Plotly:如何使用 plotly 和 plotly express 绘制回归线?

        时间:2023-09-28

          <small id='zTWEC'></small><noframes id='zTWEC'>

        1. <i id='zTWEC'><tr id='zTWEC'><dt id='zTWEC'><q id='zTWEC'><span id='zTWEC'><b id='zTWEC'><form id='zTWEC'><ins id='zTWEC'></ins><ul id='zTWEC'></ul><sub id='zTWEC'></sub></form><legend id='zTWEC'></legend><bdo id='zTWEC'><pre id='zTWEC'><center id='zTWEC'></center></pre></bdo></b><th id='zTWEC'></th></span></q></dt></tr></i><div id='zTWEC'><tfoot id='zTWEC'></tfoot><dl id='zTWEC'><fieldset id='zTWEC'></fieldset></dl></div>
        2. <legend id='zTWEC'><style id='zTWEC'><dir id='zTWEC'><q id='zTWEC'></q></dir></style></legend>

          <tfoot id='zTWEC'></tfoot>
              <bdo id='zTWEC'></bdo><ul id='zTWEC'></ul>
                <tbody id='zTWEC'></tbody>

                • 本文介绍了Plotly:如何使用 plotly 和 plotly express 绘制回归线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  I have a dataframe, df with the columns pm1 and pm25. I want to show a graph(with Plotly) of how correlated these 2 signals are. So far, I have managed to show the scatter plot, but I don't manage to draw the fit line of correlation between the signals. So far, I have tried this:

                  denominator=df.pm1**2-df.pm1.mean()*df.pm1.sum()
                  print('denominator',denominator)
                  m=(df.pm1.dot(df.pm25)-df.pm25.mean()*df.pm1.sum())/denominator
                  b=(df.pm25.mean()*df.pm1.dot(df.pm1)-df.pm1.mean()*df.pm1.dot(df.pm25))/denominator
                  y_pred=m*df.pm1+b
                  
                  
                  lineOfBestFit = go.Scattergl(
                      x=df.pm1,
                      y=y_pred,
                      name='Line of best fit',
                      line=dict(
                          color='red',
                      )
                  )
                  
                  data = [dataPoints, lineOfBestFit]
                  figure = go.Figure(data=data)
                  
                  figure.show()
                  
                  

                  Plot:

                  How can I make the lineOfBestFit to be drawn properly?

                  解决方案

                  Update 1:

                  Now that plotly express handles data of both long and wide format (the latter in your case) like a breeze, the only thing you need to plot a regression line is:

                  fig = px.scatter(df, x='X', y='Y', trendline="ols")
                  

                  Complete code snippet for wide data at the end of the question

                  If you'd like the regression line to stand out, you can edit the line color directly through:

                  fig.data[1].line.color = 'red'
                  

                  You can access regression parameters like alpha and beta through:

                  model = px.get_trendline_results(fig)
                  alpha = model.iloc[0]["px_fit_results"].params[0]
                  beta = model.iloc[0]["px_fit_results"].params[1]
                  

                  And you can even request non-linear fit through:

                  fig = px.scatter(df, x='X', y='Y', trendline="lowess")
                  

                  And what about those long formats? That's where plotly express reveals some of its real powers. If you take the built-in dataset px.data.gapminder as an example, you can trigger individual lines for an array of countries by specifying color="continent":

                  Complete snippet for long format

                  import plotly.express as px
                  
                  df = px.data.gapminder().query("year == 2007")
                  fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent", trendline="lowess")
                  fig.show()
                  

                  And if you'd like even more flexibility with regards to model choice and output, you can always resort to my original answer to this post below. But first, here's a complete snippet for those examples at the start of my answer:

                  Complete snippet for wide data

                  import plotly.graph_objects as go
                  import plotly.express as px
                  import statsmodels.api as sm
                  import pandas as pd
                  import numpy as np
                  import datetime
                  
                  # data
                  np.random.seed(123)
                  numdays=20
                  X = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()
                  Y = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()
                  df = pd.DataFrame({'X': X, 'Y':Y})
                  
                  # figure with regression
                  # fig = px.scatter(df, x='X', y='Y', trendline="ols")
                  fig = px.scatter(df, x='X', y='Y', trendline="lowess")
                  
                  # make the regression line stand out
                  fig.data[1].line.color = 'red'
                  
                  # plotly figure layout
                  fig.update_layout(xaxis_title = 'X', yaxis_title = 'Y')
                  
                  fig.show()
                  


                  Original answer:

                  For regression analysis I like to use statsmodels.api or sklearn.linear_model. I also like to organize both the data and regression results in a pandas dataframe. Here's one way to do what you're looking for in a clean and organized way:

                  Plot using sklearn or statsmodels:

                  Code using sklearn:

                  from sklearn.linear_model import LinearRegression
                  import plotly.graph_objects as go
                  import pandas as pd
                  import numpy as np
                  import datetime
                  
                  # data
                  np.random.seed(123)
                  numdays=20
                  
                  X = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()
                  Y = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()
                  df = pd.DataFrame({'X': X, 'Y':Y})
                  
                  # regression
                  reg = LinearRegression().fit(np.vstack(df['X']), Y)
                  df['bestfit'] = reg.predict(np.vstack(df['X']))
                  
                  # plotly figure setup
                  fig=go.Figure()
                  fig.add_trace(go.Scatter(name='X vs Y', x=df['X'], y=df['Y'].values, mode='markers'))
                  fig.add_trace(go.Scatter(name='line of best fit', x=X, y=df['bestfit'], mode='lines'))
                  
                  # plotly figure layout
                  fig.update_layout(xaxis_title = 'X', yaxis_title = 'Y')
                  
                  fig.show()
                  

                  Code using statsmodels:

                  import plotly.graph_objects as go
                  import statsmodels.api as sm
                  import pandas as pd
                  import numpy as np
                  import datetime
                  
                  # data
                  np.random.seed(123)
                  numdays=20
                  
                  X = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()
                  Y = (np.random.randint(low=-20, high=20, size=numdays).cumsum()+100).tolist()
                  
                  df = pd.DataFrame({'X': X, 'Y':Y})
                  
                  # regression
                  df['bestfit'] = sm.OLS(df['Y'],sm.add_constant(df['X'])).fit().fittedvalues
                  
                  # plotly figure setup
                  fig=go.Figure()
                  fig.add_trace(go.Scatter(name='X vs Y', x=df['X'], y=df['Y'].values, mode='markers'))
                  fig.add_trace(go.Scatter(name='line of best fit', x=X, y=df['bestfit'], mode='lines'))
                  
                  
                  # plotly figure layout
                  fig.update_layout(xaxis_title = 'X', yaxis_title = 'Y')
                  
                  fig.show()
                  

                  这篇关于Plotly:如何使用 plotly 和 plotly express 绘制回归线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  上一篇:在 plotly 上绘制日期与时间的关系图 下一篇:Plotly:带有“href"的树形图元素不工作

                  相关文章

                • <small id='eQhTU'></small><noframes id='eQhTU'>

                • <i id='eQhTU'><tr id='eQhTU'><dt id='eQhTU'><q id='eQhTU'><span id='eQhTU'><b id='eQhTU'><form id='eQhTU'><ins id='eQhTU'></ins><ul id='eQhTU'></ul><sub id='eQhTU'></sub></form><legend id='eQhTU'></legend><bdo id='eQhTU'><pre id='eQhTU'><center id='eQhTU'></center></pre></bdo></b><th id='eQhTU'></th></span></q></dt></tr></i><div id='eQhTU'><tfoot id='eQhTU'></tfoot><dl id='eQhTU'><fieldset id='eQhTU'></fieldset></dl></div>
                    <bdo id='eQhTU'></bdo><ul id='eQhTU'></ul>

                  1. <tfoot id='eQhTU'></tfoot><legend id='eQhTU'><style id='eQhTU'><dir id='eQhTU'><q id='eQhTU'></q></dir></style></legend>