Search code examples
pythonplotly

Fully display the amount in horizontal bar chart


With fig.update_traces(textposition="outside", textangle=0 ), chart plus text over the background will not able to fully display.

With fig.update_traces(textposition="inside", textangle=0 ), chart too short will not fully display the text amount as well.

So, is there any way to make it win-win situation?

fig = px.bar(pie_bar_gp, x='Amount', y='Product', title='Pie-Bar' ,orientation='h' 
                ,text='Amount', text_auto=",.2f"
                )      
    

    fig.update_layout(barmode="group")
    fig.update_layout({
          'paper_bgcolor': 'rgba(0, 0, 0, 0)',
        })
    

chart with:

    fig.update_traces(textposition="inside", textangle=0 )

![image|690x188](upload://itwN8pXp4HPSycsibR7ZPvwgKct.png)

 fig.update_traces(textposition="outside", textangle=0 )

![image|690x197](upload://cIcIYzOI9rI0Ydaa8vEopiE23M.png)


Solution

  • In such cases, you can pass a list of the positions you wish to display for each value. The example in the reference is forced to limit the range of the x-axis, creating the same situation as your assignment. I have set my threshold as 25, anything below that is outside and everything else is inside.

    import plotly.express as px
    
    data_Rwanda = px.data.gapminder().query("country == 'Rwanda'")
    txt_position = ['outside' if x <= 25 else 'inside' for x in data_canada['lifeExp']]
    
    fig = px.bar(data_Rwanda, x='lifeExp', y='year', orientation='h',text='lifeExp',text_auto=',.2f')
    
    fig.update_xaxes(range=[23,50])
    fig.update_traces(textposition=txt_position, textfont=dict(color='red', size=14))
    fig.update_layout(autosize=True, height=600)
    fig.show()
    

    enter image description here