pythonplotlyplotly.graph-objects

How do I set custom axis titles for a go.Figure()?


I have a graph objects Figure and I want to set custom axis titles. I've found how to do it with update_layout() for plotly express figures, but I haven't found a way to do it with a go.Figure(). (Using that instead of a plotly express graph because I'm not sure how to graph an exponential function using plotly express.)

Code:

import numpy as np
import plotly.graph_objects as go
import plotly.io as pio
pio.templates.default = "none"

x = np.linspace(0, 10,100)

graph = go.Scatter(x=x, y=100*pow(1/2, x), 
                      mode='lines', 
                      line_width=2, line_color='red',)

layout = go.Layout(title='My Graph')

fig = go.Figure(data=[graph], layout=layout)

# want to set axis titles!

fig.show()

How can I set custom axis titles?


Solution

  • To set a custom title you can configure a dictionary for the "xaxis" or "yaxis" property of go.Layout()

    import numpy as np
    import plotly.graph_objects as go
    import plotly.io as pio
    pio.templates.default = "none"
    
    x = np.linspace(0, 10,100)
    
    graph = go.Scatter(x=x, y=100*pow(1/2, x), 
                          mode='lines', 
                          line_width=2, line_color='red',)
    
    layout = go.Layout(
        title='My Graph', 
        xaxis={
            "title" : {
                "text" : "My custom x axis title"
            },
        },
        yaxis={
            "title" : {
                "text" : "My custom y axis title"
            }
        }
    )
    
    fig = go.Figure(data=[graph], layout=layout)
    
    
    
    fig.show()
    

    another valid notion would be:

    import numpy as np
    import plotly.graph_objects as go
    import plotly.io as pio
    pio.templates.default = "none"
    
    x = np.linspace(0, 10,100)
    
    graph = go.Scatter(x=x, y=100*pow(1/2, x), 
                          mode='lines', 
                          line_width=2, line_color='red',)
    
    layout = go.Layout(
        title='My Graph', 
        xaxis=dict(
            title=dict(text="My custom x axis title")
        ),
        yaxis=dict(
            title=dict(text="My custom y axis title")
        )
    )
    
    fig = go.Figure(data=[graph], layout=layout)
    
    
    fig.show()