Show a certain number of plot plotly

I’m trying to make a daily balance report that using plotly Scatter chart to show balance fluctuations daily. My idea is make a raw data folder, put raw data in there daily, use glob to open all files and use this to make Chart. Below is my sample code:

        df1 = pd.DataFrame({'Date': ['23/09/2021','24/09/2021','25/09/2021','26/09/2021','27/09/2021','28/09/2021','29/09/2021'],
                            'Balance': [1000,1050,950,875,930,1025,975]})
        print(df1)
    
             Date  Balance
    0  23/09/2021     1000
    1  24/09/2021     1050
    2  25/09/2021      950
    3  26/09/2021      875
    4  27/09/2021      930
    5  28/09/2021     1025
    6  29/09/2021      975
fig = go.Figure()
fig.add_trace(go.Scatter(
        x=df1['Date'],
        y=df1['Balance'],
        mode='lines+markers+text',
        text=df1['Balance'],
        textposition='top center'))

fig.update_traces(texttemplate='%{text:,}')
fig.update_layout(title={'text':"Daily balance",'x':0.5,'xanchor':'center'},plot_bgcolor='rgba(0,0,0,0)')
fig.update_xaxes(showline=False,showgrid=False)
fig.update_yaxes(showline=False,showgrid=False)
fig.show()

enter image description here

It’s worked well but I just want to show just recent 6 days (from 24/09/2021 ~ 29/09/2021). How can I do? Thanks and best regards.

Answer

  • use Plotly Express
  • can filter data frame to just data you want to plot
  • note conversion of Date column to date time
df1 = pd.DataFrame({'Date': ['23/09/2021','24/09/2021','25/09/2021','26/09/2021','27/09/2021','28/09/2021','29/09/2021'],
                            'Balance': [1000,1050,950,875,930,1025,975]})
df1["Date"] = pd.to_datetime(df1["Date"])

fig = px.line(
    df1.loc[df1["Date"].gt(df1["Date"].max() - pd.Timedelta(days=6))],
    x="Date",
    y="Balance",
    text="Balance",
).update_traces(textposition="top center", texttemplate="%{text:,}")
fig.update_layout(
    title={"text": "Daily balance", "x": 0.5, "xanchor": "center"},
    plot_bgcolor="rgba(0,0,0,0)",
)
fig.update_xaxes(showline=False, showgrid=False)
fig.update_yaxes(showline=False, showgrid=False)