Search code examples
pythonpython-3.xplotlyplotly-dashdashboard

How do I add a series of boxplots on x-axis with dates?


I want to add boxplots with an x-axis that corresponds to a set of dates.

This is my code-

fig = make_subplots(rows = 2, columns = 1)
fig.add_trace(go.Scatter(x = df['Date'], y = df['Measure']), 
row = 1, col = 1)

fig.add_trace(go.Box(y=[
        [ 0 ],
        [ 0 ],
        [ 0 ]
      ], name="Precompiled Quartiles",
     q1=[ 1, 2, 3 ], median=[ 4, 5, 6 ],
                  q3=[ 7, 8, 9 ], lowerfence=[-1, 0, 1],
                  upperfence=[5, 6, 7]), row = 2, col = 1)

fig.show()

I have tried x = and x0 = and supplying a series of date but neither has worked. Right now, the x axis is labeled 0, 1 and 2 with the code that I put above.


Solution

  • If I understood your requirement, you are looking to show dates in x-axis instead of 0,1,2. You can do that by simply by using x=[dates...] and using that in the go.Box(). If you have dates (datetime format), you can convert it to string using strftime.

    x=['01/01/2022', '02/02/2022', '03/03/2022']
    
    fig = go.Figure()
    fig.add_trace(go.Box(x=x, y=[
            [ 0 ],
            [ 0 ],
            [ 0 ]
          ], name="Precompiled Quartiles"))
    
    fig.update_traces(q1=[ 1, 2, 3 ], median=[ 4, 5, 6 ],
                      q3=[ 7, 8, 9 ], lowerfence=[-1, 0, 1],
                      upperfence=[5, 6, 7])
    
    fig.show()
    

    ...will give you

    enter image description here

    EDIT Based on recent comment, creating subplots AND showing dates for the box plot. I hope this will resolve your issue. There are some good examples here on what all is possible.

    From your updated code, I understand that you want to create 2 sub plots one below the other. First would be a scatter plot, while the second would be the boxplot that you need dates to show up in x-axis instead of 0,1,2. The same is achieved here.

    Data for scatter plot

    >> df
    Date    Measure
    0   2022-04-09 00:00:00 75
    1   2022-04-09 12:00:00 75
    2   2022-04-10 00:00:00 75
    3   2022-04-10 12:00:00 75
    4   2022-04-11 00:00:00 78
    5   2022-04-11 12:00:00 78
    6   2022-04-12 00:00:00 81
    7   2022-04-12 12:00:00 81
    8   2022-04-13 00:00:00 81
    9   2022-04-13 12:00:00 81
    

    Updated code

    x=['01/01/2022', '02/02/2022', '03/03/2022']
    
    fig = make_subplots(rows = 2, cols = 1)
    fig.add_trace(go.Scatter(x = df['Date'], y = df['Measure']), row = 1, col = 1)
    
    fig.add_trace(go.Box(x=x, y=[
            [ 0 ],
            [ 0 ],
            [ 0 ]
          ], name="Precompiled Quartiles"),
                 row=2, col=1)
    
    fig.update_traces(q1=[ 1, 2, 3 ], median=[ 4, 5, 6 ],
                      q3=[ 7, 8, 9 ], lowerfence=[-1, 0, 1],
                      upperfence=[5, 6, 7],
                     row=2, col=1)
    fig.show()
    

    Plot

    enter image description here