Search code examples
pythongraphformatplotlybar-chart

Text blocked by error bars on Plotly bar graph


I'm trying to have a bar plot with error bars and data labels but I cant find how to change the location of the text so that the error bars don't interfere with the labels. This is an example of what I currently have, and here's the code for that:

x = [1, 2, 3, 4, 5, 6]
y = [100, 90, 80, 70, 60, 50]
y_err = [5, 6, 7, 8, 9, 10]

fig = go.Figure(data=go.Bar(x=x, y=y, error_y_array=y_err, text=y, textposition="inside"))
fig.show()

I want the label to be at the bottom of the bar ideally, but any other way of ensuring that the data isn't covered works too. I need the data to be within the bar and oriented horizontally. Thank you!


Solution

  • I would simply just annotate each bar, the only valid args for textposition are `['inside', 'outside', and 'auto']. So in that case loop through the lists and add the text like so:

    import plotly.graph_objects as go
    
    x = [1, 2, 3, 4, 5, 6]
    y = [100, 90, 80, 70, 60, 50]
    y_err = [5, 6, 7, 8, 9, 10]
    
    fig = go.Figure(data=go.Bar(x=x, y=y, error_y_array=y_err))
    
    i=0
    text_height = 5
    for x_val in x:
        fig.add_annotation(
            x=x_val,
            y=text_height, 
            text=str(y[i]),
            showarrow=False,
            font=(dict(color='white'))
        )
        i = i+1
    

    Output: Bar chart, text bottom, plotly