Search code examples
pythonplotlybar-chart

Text cutoff in Plotly subplot, Python


I am trying to make a subplot with 4 bar plots to show the distributions for 4 categorical variables. I want each of these bars to show their value above them. For this I am trying a code which is similar to this one -

fig = make_subplots(rows = 2, cols = 2, shared_yaxes = True)

bar_fig1 = go.Figure()
bar_obj1 = go.Bar(x = x1, y = y1, text = y1, textposition = "outside")
bar_fig1.add_trace(bar_obj1)
fig.add_traces(bar_fig1.data, rows = 1, cols = 1)

bar_fig2 = go.Figure()
bar_obj2 = go.Bar(x = x2, y = y2, text = y2, textposition = "outside")
bar_fig2.add_trace(bar_obj2)
fig.add_traces(bar_fig2.data, rows = 1, cols = 2)

bar_fig3 = go.Figure()
bar_obj3 = go.Bar(x = x3, y = y3, text = y3, textposition = "outside")
bar_fig3.add_trace(bar_obj3)
fig.add_traces(bar_fig3.data, rows = 2, cols = 1)

bar_fig4 = go.Figure()
bar_obj4 = go.Bar(x = x4, y = y4, text = y4, textposition = "outside")
bar_fig4.add_trace(bar_obj4)
fig.add_traces(bar_fig4.data, rows = 2, cols = 2)

fig.show()

Using the above code I get a graph that looks like this -

enter image description here

As you can see, some of the bars have the text above them cut off. How can I fix this?


Solution

  • Since you didn't present any data, I created a subplot with the numbers I read from the image; specifying a range for the y-axis would prevent the annotation at the top of the graph from being cut off. Your code sets go.Figure() for each subplot unit, but it is not necessary to set it each time. It is in the form of adding to the first configured fig.

    Additional note: In the subplots of plotly, each y-axis is given a separate name: ' yaxis','yaxis2','yaxis3'... You could write code for each y-axis separately, but we have simplified it by using the implicit notation. To see the data structure of the graph, check fig.data.

    from plotly.subplots import make_subplots
    import plotly.graph_objects as go
    
    x1 = [3,1,2]
    y1 = [491,213,184]
    fig = make_subplots(rows = 2, cols = 2, shared_yaxes = True)
    
    fig.add_traces(go.Bar(x=x1, y=y1, text=y1, textposition = "outside"), rows=1, cols=1)
    fig.add_traces(go.Bar(x=x1, y=y1, text=y1, textposition = "outside"), rows=1, cols=2)
    fig.add_traces(go.Bar(x=x1, y=y1, text=y1, textposition = "outside"), rows=2, cols=1)
    fig.add_traces(go.Bar(x=x1, y=y1, text=y1, textposition = "outside"), rows=2, cols=2)
    
    fig.update_layout({'yaxis'+str(i+1): dict(range=[0,650]) for i in range(4)})
    
    fig.show()
    

    enter image description here

    If y-axis range is not specified

    enter image description here