Search code examples
python-3.xplotlydata-visualizationbar-chartdate-range

How to implement date range for bar chart


I have generated a bar chart in plotly. Every bar corresponds to a a date in x-axis. How can I implement something of a date picker widget of sort, so that I can see the bar for a particular date or for a range of dates. Is there any module already available for this job. And also could the same solution be applicable for a sunburst chart.

enter image description here


Solution

  • part 1 - Bar chart with "date picker"

    import pandas as pd
    import numpy as np
    import plotly.express as px
    
    df = pd.DataFrame({**{"date":pd.date_range("1-apr-2021", periods=100)}, **{c:np.random.uniform(i,i+1, 100) for i,c in enumerate(list("abc"))}})
    
    px.bar(df, x="date", y=list("abc")).update_layout(xaxis={"rangeslider":{"visible":True}})
    

    enter image description here

    part 2 - date picker on sunburst

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    from dash.dependencies import Input, Output, State
    import plotly.express as px
    import pandas as pd
    import numpy as np
    from jupyter_dash import JupyterDash
    
    app = JupyterDash(__name__)
    
    app.layout = html.Div(
        [
            dcc.DatePickerRange(
                id="date-picker",
                start_date=df["date"].min(),
                end_date=df["date"].max(),
                display_format="MMMM Y, DD",
            ),
            dcc.Graph(id="sunburst-fig"),
        ]
    )
    
    
    @app.callback(
        Output("sunburst-fig", "figure"),
        [Input("date-picker", "start_date"), Input("date-picker", "end_date")],
    )
    def update_graph(start_date, end_date):
        if start_date:
            dfp = df.loc[df["date"].between(*pd.to_datetime([start_date, end_date]))]
        else:
            dfp = df
    
        fig = px.sunburst(dfp.assign(day=df["date"].dt.strftime("%a"), month=df["date"].dt.strftime("%b")),
                path=["month","day"], values="a")
        return fig
    
    
    if __name__ == "__main__":
        #     app.run_server(debug=True)
        app.run_server(mode="inline")
    
    

    enter image description here