5. Understanding the Figure Object#

How to do it#

Creating and Inspecting Figures with Plotly Express#

  1. Import Plotly Express. Typically, this module is importe as px

import plotly.express as px
  1. Create a Figure using the Plotly Express function line, and check its type

fig = px.line(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16],  markers=True,
              title="Hello Plotly Express!")

type(fig)
plotly.graph_objs._figure.Figure
  1. Use the method show to render the Figure

fig.show()
  1. Inspect the two main attributes of a Figure object, namely data and layout

fig.data
(Scatter({
     'hovertemplate': 'x=%{x}<br>y=%{y}<extra></extra>',
     'legendgroup': '',
     'line': {'color': '#636efa', 'dash': 'solid'},
     'marker': {'symbol': 'circle'},
     'mode': 'lines+markers',
     'name': '',
     'orientation': 'v',
     'showlegend': False,
     'x': array([0, 1, 2, 3, 4]),
     'xaxis': 'x',
     'y': array([ 0,  1,  4,  9, 16]),
     'yaxis': 'y'
 }),)
fig.layout
Layout({
    'legend': {'tracegroupgap': 0},
    'template': '...',
    'title': {'text': 'Hello Plotly Express!'},
    'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'x'}},
    'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'y'}}
})

Creating the same Figure with Plotly Graph Objects#

  1. Import the Plotly Graph Objects module. Typically this is importe as go

import plotly.graph_objects as go
  1. Create an empty Figure object with go and check its type

fig = go.Figure()
type(fig)
plotly.graph_objs._figure.Figure
  1. Render your object using the method show. Notice that this figure is completely empty.

fig.show()
  1. Inspect the two main attributes of a Figure object, namely data and layout

fig.data
()
fig.layout
Layout({
    'template': '...'
})
  1. Here we are going to reproduce the scatter plot that we made with Plotly Express. To do this, start by creating a new empty Figure object. Then use the methods

  • add_trace

  • update_layout

to add the scatter, and customise the title and the axis labels, respectively. Finally, use the method show to render your figure.

fig = go.Figure()
fig.add_trace(go.Scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16]))
fig.update_layout(title="Hello Plotly Go!", xaxis_title="x", yaxis_title="y")
fig.show()
  1. Inspect the data and layout attributes for this new figure.

fig.data
(Scatter({
     'x': [0, 1, 2, 3, 4], 'y': [0, 1, 4, 9, 16]
 }),)
fig.layout
Layout({
    'template': '...',
    'title': {'text': 'Hello Plotly Go!'},
    'xaxis': {'title': {'text': 'x'}},
    'yaxis': {'title': {'text': 'y'}}
})