How to retain 1 label on yaxis for facet plot in plotly?

Question:

I got this example from https://plotly.com/python/facet-plots/. How do I make the yaxis label to have only 1 label "lifeExp", instead of all yaxes of the plots have label?

import plotly.express as px

df = px.data.gapminder().query("continent == 'Africa'")

fig = px.line(df, x="year", y="lifeExp", facet_col="country", facet_col_wrap=7,
              facet_row_spacing=0.04, # default is 0.07 when facet_col_wrap is used
              facet_col_spacing=0.04, # default is 0.03
              height=600, width=800,
              title="Life Expectancy in Africa")
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.update_yaxes(showticklabels=True)
fig.show()

enter image description here

Asked By: snow

||

Answers:

You can remove the title of y-axis of each plot and then add annotation for the entire layout, similarly the x-axis:

import plotly.express as px

df = px.data.gapminder().query("continent == 'Africa'")

fig = px.line(df, x="year", y="lifeExp", facet_col="country", facet_col_wrap=4,
              facet_row_spacing=0.02,
              facet_col_spacing=0.02, 
              height=1200, width=1000,
              title="Life Expectancy in Africa")


fig.add_annotation(text=fig['layout']['yaxis']['title']['text'],
                  xref="paper", yref="paper",
                  x=-0.07, y=0.5, showarrow=False,textangle=-90)

fig.add_annotation(text=fig['layout']['xaxis']['title']['text'],
                  xref="paper", yref="paper",
                  x=0.5, y=-0.07, showarrow=False)


fig.update_yaxes(title="")
fig.update_xaxes(title="")
fig.show()

enter image description here

Answered By: Hamzah
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.