How to show value in text (not hover) in Boxplot q1, q3, fences ... with px.box?

Viewed 1475
import plotly.express as px
px.box(df, x="people_num")

I can hover the mouse to show the value.

However, I want annotation always on because I am going to export into PNG to put into my report. Median, q1, q3, fences, ...

How can I show the value ?

Solution: plotly.express cannot make annotation always show out-of-the-box (no True/False flag to turn on-off) . You should add annotated yourself.

1 Answers

I don't believe there is a way to do this in Plotly. You will need to recalculate these values (as I could not figure out a way to access them from the fig object), and then add them using annotations. A zip function can consolidate the code a bit.

NOTE: Plotly's linear method for quartile calculation, and pandas linear method for quartile calculation don't seem to yield exactly the same results for Q1 and Q3, but hopefully the general method in my answer is still useful to you. If you don't mind that the solution isn't generalizable but you just need a boxplot with the values labelled, you can just directly pass the values and their corresponding names directly to zip([],[...]) in the code block below.

import pandas as pd
import plotly.express as px

## create some random data that looks similar
df = pd.DataFrame({'people_num':[2,10,15,16,18,20,25,26,26,27,35,36,37,52]})
fig = px.box(df, x="people_num")

## loop through the values you want to label and add them as annotations
for x in zip(["min","q1","med","q3","max"],df.quantile([0,0.25,0.5,0.75,1]).iloc[:,0].values):
    fig.add_annotation(
        x=x[1],
        y=0.3,
        text=x[0] + ":" + str(x[1]),
        showarrow=False
        )

fig.show()

enter image description here

Related