Search code examples
pythonpython-3.xplotlyplotly-dashdashboard

How do I add text labels to boxplots?


I have a series of boxplots and I want to add text labels on top of them.

This is my code-

fig = go.Figure()

fig.add_trace(go.Box(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()

I want the first boxplot to say "apples", the second to say "bananas" and the third to say "oranges." I want the text to be on top of the box plots, similar to the example under "Controlling Maximum Text Size" here.

I tried using text = . If go.Box() does not support text labeling, perhaps we can do something with scatter like in the "Vertical and Horizontal Lines Positioned Relative to the Axis Data" example here. I have at least thirty annotations to add in the real version, so I am hesitant to use something like hard-coded, individual add_annotations.


Solution

  • you can use add_annotation to add your text. The positions will be available for each of the box plots with x=0,1,2 and y will be the q3 values. Using yshift to adjust so that the text is just above the box, the text labels can be added. I have used an array and for loop to make it easier.

    fig = go.Figure()
    fig.add_trace(go.Box(y=[
            [ 0 ],
            [ 0 ],
            [ 0 ]
          ], name="Precompiled Quartiles"))
    
    Names = ['apples', 'bananas', 'oranges']
    Q3=[ 7, 8, 9 ]
    
    fig.update_traces(q1=[ 1, 2, 3 ], median=[ 4, 5, 6 ],
                      q3=Q3, lowerfence=[-1, 0, 1],
                      upperfence=[5, 6, 7])
    
    for i in range(3):
        fig.add_annotation(x=i, y=Q3[i], text=Names[i], yshift=10, showarrow=False)
    
    fig.show()
    

    which will give you below plot...

    enter image description here