Issue
I am working in a Jupyter Notebook trying to display a line chart being animated. (Seeing it being plotted from left to right.)
However, the chart doesn't show up while the chart container and all controls do show up. It is like the line is invisible.
This is my code:
import pandas as pd
import plotly.express as px
import plotly.io as pio
data = [['Year', 'Country', 'Output', 'Investment', 'Depreciation'], ['2020', 'Netherlands', 1, 2, 1], ['2021', 'Netherlands', 2, 2, 1], ['2022', 'Netherlands', 3, 2, 1], ['2023', 'Netherlands', 4, 2, 1]]
df = pd.DataFrame(data[1:], columns=data[0])
pio.renderers.default = 'notebook'
px.line(df,
x='Year',
y='Output',
color='Country',
title='Macroeconomic variables over time',
range_x=[df['Year'].iloc[0], df['Year'].iloc[-1]],
range_y=[0, max(df['Output']) * 1.25],
animation_frame='Year')
Giving the following chart (in both VSCode and Jupyter Notebooks):
Any ideas on why this happens?
Solution
- fundamentally you need to think about the dimensions of your data. Given there is one row per Year and you are using as animation_frame each trace will have only one point in it. This does not make a line
- have simulated a slightly different data frame, that has Decade and used as animation_frame. This then means there are 10 rows, hence 10 points per trace that makes a line.
import pandas as pd
import plotly.express as px
import numpy as np
data = [
["Year", "Country", "Output", "Investment", "Depreciation"],
["2020", "Netherlands", 1, 2, 1],
["2021", "Netherlands", 2, 2, 1],
["2022", "Netherlands", 3, 2, 1],
["2023", "Netherlands", 4, 2, 1],
]
df = pd.DataFrame(data[1:], columns=data[0])
df = pd.DataFrame(
{
c: list(range(2000 if i == 0 else 1, 2050 if i == 0 else 51, 1))
if c in ["Year", "Output"]
else np.full(50, i if c != "Country" else "Netherlands")
for i, c in enumerate(data[0])
}
).assign(Decade=lambda d: d["Year"] // 10 - 200)
px.line(
df,
x="Year",
y="Output",
color="Country",
title="Macroeconomic variables over time",
range_x=[df["Year"].iloc[0], df["Year"].iloc[-1]],
range_y=[0, max(df["Output"]) * 1.25],
animation_frame="Decade",
)
Answered By - Rob Raymond
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.