5. Understanding the Figure Object#
How to do it#
Creating and Inspecting Figures with Plotly Express#
Import Plotly Express. Typically, this module is importe as
px
import plotly.express as px
Create a
Figure
using the Plotly Express functionline
, and check itstype
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
Use the method
show
to render theFigure
fig.show()
Inspect the two main attributes of a
Figure
object, namelydata
andlayout
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#
Import the Plotly Graph Objects module. Typically this is importe as
go
import plotly.graph_objects as go
Create an empty
Figure
object withgo
and check its type
fig = go.Figure()
type(fig)
plotly.graph_objs._figure.Figure
Render your object using the method
show
. Notice that this figure is completely empty.
fig.show()
Inspect the two main attributes of a
Figure
object, namelydata
andlayout
fig.data
()
fig.layout
Layout({
'template': '...'
})
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()
Inspect the
data
andlayout
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'}}
})