Search code examples
pythonplotlyplotly-express

Plotly: How to add text labels to a histogram?


Is there a way how to display the counted value of the histogram aggregate in the Plotly.Express histogram?

px.histogram(pd.DataFrame({"A":[1,1,1,2,2,3,3,3,4,4,4,5]}),x="A") enter image description here If I would use regular histogram, I can specify text parameter which direct to the column which contain the value to display.

px.bar(pd.DataFrame({"val":[1,2,3,4,5], "height": [3,2,3,3,1]}), x="val", y="height", text="height") enter image description here

But with histograms, this value is calculated and it's not even part of the fig.to_dict(). Is there a way to add the text labels into histogram?

Using the answers below, I've summarized the finding to an article - https://towardsdatascience.com/histograms-with-plotly-express-complete-guide-d483656c5ad7


Solution

  • As far as I know, plotly histograms do not have a text attribute. It also turns out that it's complicated if at all possible to retrieve the applied x and y values and just throw them into appropriate annotations. Your best option seems to be to take care of the binning using numpy.histogram and the set up your figure using go.Bar. The code snippet below will produce the following plot:

    enter image description here

    Complete code:

    import numpy as np
    import plotly.express as px
    import plotly.graph_objects as go
    
    # sample data
    df = px.data.tips()
    
    # create bins
    bins = [0, 10, 20, 30, 40, 50]
    counts, bins = np.histogram(df.total_bill, bins=bins)
    #bins2 = 0.5 * (bins1[:-1] + bins2[1:])
    
    fig = go.Figure(go.Bar(x=bins, y=counts))
    fig.data[0].text = counts
    fig.update_traces(textposition='inside', textfont_size=8)
    fig.update_layout(bargap=0)
    
    
    fig.update_traces(marker_color='blue', marker_line_color='blue',
                      marker_line_width=1, opacity=0.4)
    
    fig.show()