Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 31 ยท Plotly

Plotly Figures: Data, Layout and Traces

Understand a Plotly figure as plain JSON: traces, layout and config, graph_objects versus Express, update_layout and add_trace, with a Python validator.

Every Plotly chart, whatever language made it, is the same thing underneath: a block of JSON with a list of traces and a layout. Plotly Express, graph_objects, R, Julia and plotly.js all produce or accept that same structure. Once you can read it, you can debug a chart by looking at its data, build figures without any helper, and move a chart between languages.

The Plotly library cannot run on this site, so the Plotly code below is read-only. The runnable examples are stand-ins in Python: they build and check plain dictionaries shaped like a Plotly figure. They are not the real library, which validates every property against a large schema, but the structure and the rules you practise are the real ones. If you have not met px yet, start with Plotly Express Basics.

A figure has three parts

data A list of traces, the things drawn.
layout Title, axes, legend, size, template.
config How the page behaves, not what it shows.

data and layout are the figure; config is passed when you show it.

1 / 2

A figure is a dictionary

Here is a complete Plotly figure written as plain Python. It draws one line and one set of bars on the same axes. This is the shape every Figure has, and it is read-only:

Python
figure = {
    "data": [
        {"type": "scatter", "mode": "lines+markers", "name": "Units",
         "x": ["Jan", "Feb", "Mar"], "y": [120, 150, 90]},
        {"type": "bar", "name": "Target",
         "x": ["Jan", "Feb", "Mar"], "y": [100, 100, 100]},
    ],
    "layout": {
        "title": {"text": "Units against target"},
        "xaxis": {"title": {"text": "Month"}},
        "yaxis": {"title": {"text": "Units"}, "rangemode": "tozero"},
        "legend": {"orientation": "h"},
    },
}

Each entry in data is a trace. A trace has a type (scatter, bar, histogram, heatmap, pie, ...) and the properties that type understands. The properties fall into groups:

  • Data: x, y, z, labels, values, text, customdata.
  • Appearance: mode, marker (color, size, symbol), line (color, width, dash), opacity.
  • Behavior: name (the legend text), hovertemplate, visible, showlegend.

The layout holds everything that belongs to the whole chart rather than to one trace: title, xaxis and yaxis, legend, width, height, margin, template, annotations, shapes, and the barmode for bars. Notice that a trace never describes the axis it uses: the axis lives in the layout, and the trace only points at it.

Nested properties can be written as nested dictionaries, or in Python as "magic underscore" names such as title_text and marker_color. In a dictionary the underscore version expands to the nested form: "marker_color": "red" and "marker": {"color": "red"} mean the same.

Building the same figure with graph_objects

plotly.graph_objects (usually imported as go) is the explicit builder. Each trace is a class, and the Figure collects them. This is read-only code:

Python
import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Scatter(x=["Jan", "Feb", "Mar"], y=[120, 150, 90],
                         mode="lines+markers", name="Units"))
fig.add_trace(go.Bar(x=["Jan", "Feb", "Mar"], y=[100, 100, 100],
                     name="Target"))
fig.update_layout(title_text="Units against target",
                  xaxis_title="Month", yaxis_title="Units",
                  legend_orientation="h")

The result is exactly the dictionary above: fig.to_dict() returns it, and fig.to_json() returns it as text. The classes add two helpful things. They validate as you type, so a misspelled property such as colour raises an error naming the valid options instead of being ignored, and your editor can autocomplete property names.

The three methods you will use most:

Method What it changes
fig.add_trace(trace) Appends a trace to data
fig.update_layout(...) Merges new values into layout; existing keys you do not mention stay
fig.update_traces(...) Changes properties on every trace, or only some with selector=

The word merge is important. update_layout(xaxis_title="Month") changes one nested key and keeps the rest of xaxis untouched. That is different from replacing a dictionary, and the first stand-in below makes the difference visible.

Express or graph_objects?

Use Express when your data is a table and you want a standard chart fast. Use graph_objects when you need a trace type or option that Express does not offer, when you combine different trace types (like the line and bars above), or when your data is not in a DataFrame. They are not rivals: an Express figure is a Figure, so you can call add_trace on it afterwards. In practice you draw the base chart with px and then adjust it with go objects and update_* calls.

Config is not part of the figure

A third object, config, is passed when the figure is displayed. It controls the page around the chart: whether the toolbar appears, whether scrolling zooms, the image-download format, and whether the chart resizes with its window.

Python
fig.show(config={"displaylogo": False, "scrollZoom": True,
                 "toImageButtonOptions": {"format": "png", "filename": "units"}})

Keep the line clear in your head: layout is what the chart looks like and is saved in the figure; config is how the viewer's page treats it, and is not part of fig.to_dict().

Building and merging a figure

The first stand-in builds the figure as a dictionary, adds a trace, and applies a update_layout-style merge. The merge function walks nested dictionaries the way Plotly does, so only the keys you name are changed.

Python Build a figure dict and merge layout updates

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.

After the second merge, the x-axis title reads Calendar month while "type": "category" is still there. If you had assigned fig["layout"]["xaxis"] = {...} instead, the type would be gone. That is the difference between merging and replacing, and it is the reason update_layout is safe to call repeatedly.

Checking a figure's shape

Because a figure is data, you can check it. Real Plotly raises an error for an unknown property as soon as you build a go object. The stand-in below has a much smaller rule list, but it tests the mistakes people really make: a trace with no type, x and y of different lengths, a trace type that Plotly does not have, and a misspelled layout key.

Python Validate the shape of 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.

The bad figure produces four problems, one of them a layout typo that a silent system would simply ignore, leaving you wondering why the title never appears. Checking structure like this, instead of looking at pixels, is the idea behind Testing Charts and Common Pitfalls.

Why this matters

Because a figure is JSON, it travels. Python can send it to a web page, a Dash app, or a different language. fig.to_json() gives you text that plotly.js accepts directly in the browser, which is what Plotly.js in the Browser builds on. You can store figures in a database, compare two versions to see what changed, and generate charts from templates. The attention to structure also pays off when you style: nearly every look-and-feel change is a path into layout or a trace, covered in Plotly Styling, Templates and Annotations.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the two main parts of a Plotly figure?

    A figure holds a list of traces in data and everything that belongs to the whole chart in layout.
  2. 2. Which belongs in layout rather than in a trace?

    Axes belong to the chart as a whole, so their titles live in layout. A trace only points at the axis it uses.
  3. 3. What does fig.update_layout(xaxis_title="Month") do to the other keys inside xaxis?

    update_layout merges into the existing layout, so only the named nested key changes.
  4. 4. When should you reach for graph_objects instead of Plotly Express?

    graph_objects gives explicit control trace by trace. Both produce the same Figure, so you can mix them.
  5. 5. Where does the config object, for example scrollZoom, apply?

    Config is not part of fig.to_dict(). It is given to show or to plotly.js when the chart is displayed.

Summary

  • A Plotly figure is plain JSON: data (a list of traces) and layout.
  • Each trace has a type and the properties that type understands; axes, titles and legend belong to the layout.
  • graph_objects builds a figure trace by trace with validation; Express builds one in a call; both give the same Figure.
  • add_trace, update_layout and update_traces change a figure, and updates merge into what is there.
  • Config controls the viewer's page, not the chart content.
  • The Plotly calls are read-only here; the dictionary code is a stand-in with a smaller rule set than the real schema.

Next: Plotly Styling, Templates and Annotations.