Luca König
Luca König

Reputation: 90

Plotly: How to plot time series in Dash Plotly

I've searched for days and didn't find an answer. How can I plot a time series data in Dash Plotly as a linegraph with selectable lines?

My data (pandas dataframe) describes GDP of different countrys. Index is country, column is years.

enter image description here

I don't find a solution to pass the data to Dash Plotly linegraph. What are my x and y values?

fig = px.line(df, x=?, y=?)

Upvotes: 4

Views: 5821

Answers (1)

vestland
vestland

Reputation: 61234

By the looks of it, the solution in your example should be:

fig = px.line(df, x=df.index, y = df.columns)

Plot 1 - plot by columns as they appear in your dataset

enter image description here

From here, if you'd like to display countries in the legend and have time on the x-axis, you can just add df = df.T into the mix and get:

Plot 2 - transposed dataframe to show time on the x-axis

enter image description here

Details

There's a multitude of possibilites when it comes to plotting time series with plotly. Your example displays a dataset of a wide format. With the latest versions, plotly handles both datasets of long and wide format elegantly straight out of the box. If you need specifics of long and wide data in plotly you can also take a closer look here.

The code snippet below uses the approach described above, but in order for this to work for you exactly the same way, your countries will have to be set as the dataframe row index. But you've stated that they are, so give it a try and let me know how it works out for you. And one more thing: you can freely select which traces to display by clicking the years in the plot legend. The figure produced by the snippet below can also be directly implemented in Dash by following the steps under the section What About Dash? here.

Complete code:

import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio

import plotly.io as pio

# sample dataframe of a wide format
np.random.seed(5); cols = ['Canada', 'France', 'Germany']
X = np.random.randn(6,len(cols))  
df=pd.DataFrame(X, columns=cols)
df.iloc[0]=0;df=df.cumsum()
df['Year'] =  pd.date_range('2020', freq='Y', periods=len(df)).year.astype(str)
df = df.T
df.columns = df.iloc[-1]
df = df.head(-1)
df.index.name = 'Country'

# Want time on the x-axis? ###
# just include:
# df = df.T
##############################

# plotly
fig = px.line(df, x=df.index, y = df.columns)
fig.update_layout(template="plotly_dark")
fig.show()

Upvotes: 4

Related Questions