Skip to content
Advertisement

Plotly: How to display a regression line for one variable against multiple other time series?

With a dataset such as time series for various stocks, how can you easily display a regression line for one variable against all others and quickly define a few aesthetic elements such as:

  1. which variable to plot against the others,
  2. theme color for the figure,
  3. colorscale for the traces
  4. type of trendline; linear or non-linear?

Data:

JavaScript

Reproducible through:

JavaScript

Advertisement

Answer

The essence:

JavaScript

The details:

With the latest versions of plotly.express (px) and px.scatter, these things are both easy, straight-forward and flexible at the same time. The snippet below will do exactly as requested in the question.

First, define a target = 'GOOG from the dataframe columns. Then, using `px.scatter() you can:

  1. Plot the rest of the columns against the target using y = [c for c in df.columns if c != target]
  2. Select a theme through template='plotly_dark') or find another using pio.templates.
  3. Select a color scheme for the traces through color_discrete_sequence = px.colors.qualitative.T10 or find another using dir(px.colors.qualitative)
  4. Define trend estimation method through trendline = 'ols' or trendline = 'lowess'

(The following plot is made with a data soure of a wide format. With some very slight amendments, px.scatter() will handle data of a long format just as easily.)

Plot

enter image description here

Complete code:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement