Search code examples
pythonplotly

Adding information to a plotly bar plot


Disclaimer: It may be the case that plotly is not suitable for these tasks. If so, I'll be happy to have a pointer for a library that is relevant to the task.

Given the following plotly barplot:

    fig = px.bar(
        loans_scores_df,
        x="Score",
        y="Count",
        color="Count", "features": "Features"},
        height=400,
    )

enter image description here
I'll be happy to generate a figure that summarizes the aggregated amount of scores under 0.9. One visual form of the idea I had in mind is:
enter image description here
But other forms of display are great as well.


Solution

  • There are two ways to add annotations: using the text mode for scatter plots and the add annotation function. I used the scatterplot text mode for annotations. The reason is that it is easier to set the coordinates. Also, for the arrows, I used the left and right arrows on top of each other. The arrow heads are set to style #2. As you can see in the comments of the code, the start and end positions are specified respectively, and the coordinate reference for each is x,y. If no text is used, specify blank.

    import plotly.graph_objects as go
    import numpy as np
    
    hist, bins = np.histogram(np.random.randn(40000), bins=100)
    
    fig = go.Figure(go.Bar(x=bins, y=hist, marker=dict(color=hist,)))
    
    samples = hist[:25].sum()
    
    fig.add_trace(go.Scatter(
        mode='text',
        x=[bins[25]],
        y=[hist[25]+150],
        text='{:,} samples'.format(samples),
        textfont=dict(size=24),
        textposition='top left',
        showlegend=False
        #yshift=100
    ))
    
    fig.add_annotation(
        x=bins[5],  # arrows' head
        y=hist[25],  # arrows' head
        ax=bins[24],  # arrows' tail
        ay=hist[25],  # arrows' tail
        xref='x',
        yref='y',
        axref='x',
        ayref='y',
        text='',  # if you want only the arrow
        showarrow=True,
        arrowhead=2,
        arrowsize=1,
        arrowwidth=5,
        arrowcolor='#636efa'  
    )
    
    fig.add_annotation(
        x=bins[25],
        y=hist[25],
        ax=bins[6],
        ay=hist[25],
        xref='x',
        yref='y',
        axref='x',
        ayref='y',
        text='',  
        showarrow=True,
        arrowhead=2,
        arrowsize=1,
        arrowwidth=5,
        arrowcolor='#636efa'
    )
    
    fig.show()
    

    enter image description here