pythongoogle-colaboratoryplotly-dash

Creating a interactive time series in Dash


I am trying to create a time series plot using Dash in Google Colab however I am getting the below error:

TypeError: 'NoneType' object cannot be interpreted as an integer

My code is below:

df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df['year'] = df['date'].dt.year
sales = df['sales']

app = JupyterDash(__name__)

app.layout = html.Div([
    html.H4('Sales Over Time'),
    dcc.Graph(id='time-series-chart'),
    html.P('Select Year'),
    dcc.Dropdown(
        id='year',
        options=[{'label': year, 'value': year} for year in df['year'].unique()],
        value=df['year'].min(),
        clearable=False
    )
    ])

@app.callback(
    Output('time-series-chart', 'figure'),
    Input('year', 'value')
    )

def update_line_chart(year):
  filtered_df = df[df['year'] == year]
  fig = px.line(filtered_df, x='sales', y=year)
  return fig

app.run_server(mode='inline')

It is meant to give users a drop down where they can select the year and once select produce a graph that shows sales of all sales within that year. your text


Solution

  • I think your problem comes when it comes to the graph, you have already filtered your data to only give you the specific year, but when you are creating the graph, the x axis should be the 'date' instead of year, so it will split it within the months of that specific year.

    Try having it:

    def update_line_chart(selected_year):
        filtered_df = df[df['year'] == selected_year]
        fig = px.line(filtered_df, x='date', y='sales', title=f'Sales in {selected_year}')
        return fig
    

    Otherwise please add more information to your error and give some examples of how your data frame looks.