X-axis changes when styling with width

Dear all,

I want to display the hottest years since 1900 in a top 10 format. Full width looks ok, but when I change the width to 30%, the range of values changes and the fig looks awful:

You see that the largest value on the x-axis changes from 12 to 40 degrees although there is no temperature beyond 13 degrees Celsius.

Code is:

def hottest_10(df):
    hottest = df.groupby(['Jahrzehnt','Jahr'])['Temperatur, Durchschnitt'].mean().round(2).to_frame()
    #hottest = hottest[hottest['Temperatur, Durchschnitt'] != 0]
    hottest_yrs = hottest.sort_values(by='Temperatur, Durchschnitt', ascending=False).head(10)
    hottest_yrs['Rang'] = hottest_yrs['Temperatur, Durchschnitt'].rank()
    temp_avg_all = df['Temperatur, Durchschnitt'].mean()

    fig = px.bar(hottest_yrs, x='Temperatur, Durchschnitt', y='Rang', orientation='h', color='Jahrzehnt', 
                 title='Die 10 Jahre mit den höchsten Durchschnittstemperaturen (1870-2020)')
    fig.add_vline(temp_avg_all, line_width=1, line_dash="dash", line_color="blue",
                 annotation_text="Durchschnitt 1870-2020", annotation_position="bottom right")
    return fig

and then

    html.Div(id='hottest_10_div', children=[
        #style= {'width': '30%', 'display':'inline-block'}

Does anybody has a hint how that could be corrected? Of course, the smaller width should stop at 13 degrees as well.

Thank you!


I believe the change is due to Plotly trying to fit your annotation (“Durchschnitt …”) in the plot. Not sure if this works with vline, but you can try to set annotation_textangle=-90 to rotate it vertically and stop taking plotting space. Otherwise you can add this text explicitly via add_annotation.

Thank you, Jose.

    fig.add_vline(temp_avg_all, line_width=1, line_dash="dash", line_color="blue",
                 annotation_text="Durchschnitt 1870-2020", annotation_position="top right",

solved the issue

1 Like