Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 42 ยท Getting Started

Graph Objects and Figure Anatomy

Understand the anatomy of a Plotly figure: traces in data, layout, frames, magic underscores, add_trace and the update_traces and update_layout methods with selectors.

Every Plotly chart, whether Express made it or you wrote it by hand, is a go.Figure. A figure has three parts: data (a list of traces), layout (everything that is not data) and optional frames (animation steps, covered later). If you understand these three parts you can read and change any chart.

Graph objects (plotly.graph_objects, imported as go) are the building blocks. They are more verbose than Express, but they let you combine chart types, control every attribute and build things Express cannot, such as a bar chart with a line on a second axis.

Figure, trace, layout

A trace is one data series plus the instructions for drawing it: its type (scatter, bar, histogram, pie ...), its values and its style. The figure keeps them in fig.data, a tuple of trace objects. The layout holds the title, the axes, the legend, margins, background, fonts, annotations and more.

flowchart TD
    F["go.Figure"] --> D["data (tuple of traces)"]
    F --> L["layout"]
    F --> R["frames (animation)"]
    D --> T1["Scatter: x, y, mode, marker, line"]
    D --> T2["Bar: x, y, marker_color"]
    L --> L1["title"]
    L --> L2["xaxis / yaxis"]
    L --> L3["legend, margin, template ..."]

A figure is data + layout (+ frames). Traces hold the numbers, layout holds the page.

Building a figure step by step

You can pass everything to the constructor, or start with an empty figure and add pieces. The second style is easier to read for bigger charts:

Python Build a figure from traces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two traces share the same axes: a Bar and a Scatter. This is called a combination chart. The next example draws exactly this figure:

A bar and a line in one chart

Magic underscores

Plotly properties are nested. The title text lives at layout.title.text, the y-axis title at layout.yaxis.title.text. Writing nested dictionaries gets tedious, so plotly.py lets you join the path with underscores:

Python
fig.update_layout(yaxis_title_text="USD")          # same as the next line
fig.update_layout(yaxis=dict(title=dict(text="USD")))

Shortcuts also exist: title="..." means title.text, and yaxis_title="..." means yaxis.title.text. The same trick works for traces: marker_color="red" equals marker=dict(color="red"). You can also assign with attribute syntax: fig.layout.title.text = "Hello".

Updating, adding and selecting traces

Four methods do most of the work:

Method Purpose
fig.add_trace(trace) Append one trace. There are also shortcuts like fig.add_bar(...), fig.add_scatter(...).
fig.update_traces(...) Change properties of every trace (or only some, with selector).
fig.update_layout(...) Change the layout.
fig.update_xaxes(...), fig.update_yaxes(...) Change axis properties without writing layout.xaxis.

update_traces takes a selector so you can aim at certain traces only:

Python Update some traces with a selector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The selector dict(name="Asia") matches only the trace whose name is Asia. You can select by any trace property, for example selector=dict(type="scatter"). for_each_trace runs your function on each trace for changes that depend on the trace itself.

Express and graph objects together

You can start with Express for the quick base chart and then add handmade traces. This is the most productive workflow in practice:

Python
fig = px.scatter(df, x="x", y="y", color="group")
fig.add_hline(y=0, line_dash="dash")                      # reference line
fig.add_trace(go.Scatter(x=[1, 2], y=[3, 4], name="extra"))

add_hline, add_vline and add_shape draw reference lines and shapes. They are covered in later lessons.

Reading a figure's contents

Three ways to look inside a figure are worth remembering:

  • fig.data[0] and fig.layout: objects with attribute access and tab-completion in notebooks.
  • fig.to_dict(): plain Python dictionaries and lists.
  • fig.to_json(): the exact JSON string that plotly.js receives.
Python Inspect a figure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note that data you pass in becomes a tuple inside the figure (arrays stay NumPy arrays), and assigning a new value to a property replaces it.

Frames

The third key, frames, is a list of alternative versions of data that plotly.js can play like a slideshow. Animated charts (animation_frame in Express) fill it for you. It is empty for static charts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does a figure store the chart title, axis titles and legend settings?

    data holds traces (the values and how each series is drawn); layout holds everything about the page: titles, axes, legend, margins.
  2. 2. What does fig.update_layout(yaxis_title="USD") set?

    The underscore is a shortcut for the nested path layout.yaxis.title.text.
  3. 3. How do you change the color of only the trace named Asia?

    update_traces with a selector limits the update to matching traces.
  4. 4. Which method returns the JSON string that is sent to plotly.js?

    to_json() serializes the figure. to_dict() returns the same content as Python objects.
  5. 5. True or false: you can add a go.Scatter trace to a figure that was created with px.bar.

    Express returns a normal figure, so add_trace, update_layout and all other methods work.

Summary

  • A figure is data (traces) + layout + frames.
  • A trace has a type, its values and its style; the layout controls everything around it.
  • Build with go.Figure() and add_trace, or start from Express and refine.
  • update_traces, update_layout, update_xaxes and update_yaxes change figures after the fact; use selector to target traces.
  • Magic underscores (yaxis_title, marker_color) replace nested dictionaries.

Next: Data for Plotly Charts