Search code examples
pythonrenameaxisplotly-express

Plotly Express rename axis (figure shows no axis name)


I'm trying to give a name to the axis of my graph with plotly express, but the figure shows no axis name. I would like that Y was called "$$$" and X was called "years".

Any idea of what is wrong?

Thank you!

This is my code:

def interactive_plot(df,title=f"Portfolio growth since {year}"):

  fig = px.line(title=title,labels{"y":"$$$","x":"years"})
  for i in df.columns[:]:
      fig.add_scatter(x=dates[:-1],y=df[i],name=i)

  fig.show()

Solution

  • Since we don't have any data or example output to expect, we are guessing from the code to create sample data. The data was taken from the official reference, and the long format was converted to wide format for the data. The titles of the axes were updated at the end after the graph was created, and although the graph was created using a mixture of express and graph objects, it was unified using graph objects.

    import plotly.graph_objects as go
    
    df = px.data.gapminder().query("country in ['France','Germany','Italy','United Kingdom']")
    df = df[['country','year','lifeExp']].pivot(index='year',columns='country', values='lifeExp')
    
    def interactive_plot(df,title):
    
        fig = go.Figure()
    
        for i in df.columns:
            fig.add_trace(go.Scatter(x=df.index, y=df[i], name=i))
        fig.update_layout(title=title, yaxis_title='lifeExp', xaxis_title='year')
        fig.show()
        
    interactive_plot(df,"Portfolio growth")
    

    enter image description here