Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 42 ยท Projects and Practice

Plotly Practice and Common Pitfalls

Practice Plotly with graded exercises and worked solutions, then review the most common mistakes: wrong data shapes, lost ranges, slow figures, misleading axes and unreadable colors.

Reading about charts is not the same as making them. This final lesson gives you exercises, each with a worked solution you can run, followed by a field guide to the mistakes that cost people the most time. Try every exercise yourself before you open the solution: even a failed attempt teaches you where the options live.

How to practice well

  1. Start from a question, not a chart type: "Which region is shrinking?", "Do cheaper products sell more units?".
  2. Sketch the picture on paper: axes, color, what should jump out.
  3. Build it in the simplest way (usually Plotly Express), then refine with update_layout, update_traces and update_xaxes.
  4. Inspect the figure (fig.data, fig.layout, fig.to_dict()) when something looks wrong. The figure is just data.
  5. Delete everything that does not help the reader (grid lines, extra legend, decoration).

Exercise 1: tidy the data first (beginner)

Task: The table below has one column per month. Plot revenue per month, one line per product, with Plotly Express.

Hint: px.line wants one row per observation ("long" format). Use melt.

Python Solution 1: melt wide data into long data

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.

categoryorder="array" keeps the months in calendar order. Without it, a text axis keeps the order of first appearance, which here happens to be right, but would not be after a sort.

Exercise 2: an honest comparison (intermediate)

Task: A bar chart shows two sales numbers, 980 and 1000. Make a version that does not exaggerate the difference, then add the percentage difference as an annotation.

Hint: bars encode value by length, so the axis of a bar chart must start at zero.

Python Solution 2: zero baseline and annotation

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.

A truncated axis (starting at 975, say) would make a 2 % change look like a 5x difference. Line charts may use non-zero axes because they encode change by position and slope, but bars may not.

Exercise 3: facets and shared scales (intermediate)

Task: Using the tips data, show the distribution of total_bill for each day in a separate panel, with the same x-axis everywhere, ordered Thursday to Sunday. Add the mean as a vertical line in each panel.

Python Solution 3: facet histogram with mean lines

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 rows inside a wrapped facet grid are numbered from the bottom, which surprises everybody once. When in doubt, check the result with fig.layout.shapes or draw it and look.

Exercise 4: an interactive control (advanced)

Task: Build a scatter chart of 40 points (x against y) with a dropdown that colors the points by one of two groupings, without a server.

Solution 4: restyle the marker colors (Plotly.js)

Notice the [byParity] wrapping once more: restyle takes one value per trace.

Exercise 5: your own challenges

Without solutions, so you decide what good looks like:

  1. A dashboard row of three charts sharing one date axis, from a CSV of your own.
  2. A choropleth of a measure you care about, with a log or quantile color scale and a source note.
  3. An animated bar chart that shows the five biggest values per year (a "race").
  4. A candlestick chart with moving-average lines and weekend gaps removed.
  5. A 3D surface of a function with a button row for three camera views.
  6. A Dash app with a dropdown, a slider and a graph, and a dcc.Store that remembers the filtered table.

The pitfall field guide

Data shape

  • Wide table into px. Symptom: one chart with the wrong series. Fix: melt to long format, or pass a list of columns to y.
  • Dates as strings. Symptom: wrong sort, no range selector. Fix: pd.to_datetime.
  • z for a surface or heatmap the wrong way round. Rows are y, columns are x.
  • Grouping by color on a column with 200 values. Symptom: unreadable legend. Aggregate or filter first.

Layout and axes

  • Truncated bar axes exaggerate differences. Start bars at zero.
  • Two y-axes with unrelated scales invite false correlations. Prefer two stacked charts.
  • Axis ranges that change in animation. Fix range_x and range_y.
  • Hidden titles. A chart needs a title, axis titles with units and (when several series) a legend. fig.update_layout(title=..., xaxis_title=..., yaxis_title=...).
  • Default height. Increase height for subplots and long category lists.

Color

  • Rainbow scales (jet) distort the data. Use sequential scales like Viridis or Blues for ordered values, diverging scales (RdBu) around a meaningful midpoint, and qualitative palettes for categories.
  • More than about 8 categories in color. Use facets or highlight one and gray the rest.
  • Relying on red versus green. About 8 % of men cannot tell them apart. Add shape or position cues.

Performance

  • Hundreds of thousands of points in scatter. Use scattergl or aggregate (see deploying Plotly apps).
  • Hover data on every point of a huge table. It is copied into the figure; trim the columns.
  • Dozens of figures on one page. Each loads its own copy of the template. Combine them with subplots or load them on demand.

Interactivity

  • Buttons that toggle instead of set. They get out of sync after zooming. Define buttons as absolute states.
  • Event handlers piling up when a chart is redrawn: remove listeners first.
  • State in global variables of a Dash app. Workers do not share memory; use a store, database or cache.

Output

  • write_image fails. Kaleido and a Chrome install are missing. Install them or export HTML instead.
  • Interactive HTML pasted into email. Scripts are stripped; send a PNG plus a link.
  • fig.show() in a script opens nothing. Set pio.renderers.default or use write_html.
flowchart TD
    A["Chart looks wrong"] --> B{"Data right?"}
    B -->|No| C["Check shape: long format, dtypes, NaN"]
    B -->|Yes| D{"Layout right?"}
    D -->|No| E["Inspect fig.layout: axes, ranges, domains"]
    D -->|Yes| F{"Style right?"}
    F -->|No| G["Template, color scale, fonts"]
    F -->|Yes| H["Check the config and the renderer"]

A debugging order: data first, then layout, then style, then output.

Where to go next

You now know how to build, style, animate, annotate and deploy Plotly charts. Good next steps are the Python tutorials on pandas for data preparation and the Python track for fundamentals, then your own project: a real dataset about something you care about is the best teacher. Share it, collect feedback from a real reader and iterate.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A bar chart compares 980 and 1000, and the y-axis starts at 975. What is the problem?

    Bar length encodes value, so the axis must start at zero to keep the lengths honest.
  2. 2. Your wide DataFrame has columns product, Jan, Feb, Mar. How do you give px.line one line per product over months?

    Plotly Express expects one row per observation. melt converts the wide table.
  3. 3. Which color scale is the best default for a numeric value that goes from low to high?

    Sequential scales change smoothly in lightness, so order is visible. Rainbow scales create false boundaries.
  4. 4. Which debugging order is recommended when a chart looks wrong?

    Most chart problems come from the data shape or types. Fix those before polishing layout and style.

Summary

  • Practice from questions, sketch first, build simply, inspect the figure, and remove clutter.
  • Reshape wide data to long, fix dates, and keep axis ranges stable in animations.
  • Bars start at zero; use sequential or diverging color scales and avoid red-green-only encodings.
  • Use scattergl, aggregation and lean figures for speed; keep Dash callbacks stateless.
  • When stuck, debug in order: data, layout, style, output.

Next: back to the Plotly track