Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 31 ยท Practice and Review

Practice Exercises with Solutions

Twelve data visualization exercises with runnable solutions: build chart specs, aggregate, bin, reshape, smooth, write scales, check contrast and pick a library.

Reading about charts is not the same as building them. These twelve exercises cover the ideas that Plotly, Bokeh and Altair share: a chart is a spec (plain data), a transform (rows in, rows out), a scale (data to pixels or colors), and a decision about what to show. None of them needs a charting library, because each one is the small piece of logic that the libraries hide.

How to use this page: read an exercise, try it on your own in the editor of the matching group (the solution TryIt is a good place to start from, but cover the code first), then compare. Each group of three exercises has a statement list and a solution program with checks that print ok when the answer is right. The real libraries cannot run on this site, so these are stand-ins that model what the libraries do.

flowchart LR
    S["Specs<br/>1, 2"] --> T["Transforms<br/>3, 4, 5, 6"]
    T --> C["Scales<br/>7, 8, 9"]
    C --> D["Decisions<br/>10, 11, 12"]

The exercises follow the pipeline: describe the chart, shape the data, map it to the screen, then judge the result.

Part 1: specs and aggregation (Python)

Exercise 1: a bar spec. Write bar_spec(records, x, y, title) that returns a Vega-Lite-style dictionary: the title, the records under data.values, mark set to "bar", and an encoding with x as a nominal field and y as a quantitative field. Compare with Reading and Writing Vega-Lite JSON.

Exercise 2: a figure with validation. Build a Plotly-style figure as a dictionary with two line traces (type: "scatter", mode: "lines") and a layout containing a title. Then write validate(fig) that returns a list of problems: a trace without x or y, traces whose x and y differ in length, or a missing layout title. See Plotly figures.

Exercise 3: total per category. Given sales records with category and amount, return the totals per category as a list of (category, total) pairs, sorted from largest to smallest. This is groupby plus sum, the same as a bar chart's sum(amount) encoding.

Solutions 1 to 3

Python Exercises 1 to 3: spec, validation, aggregation

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.

Exercise 2's bad figure has three problems: no layout title, a length mismatch in trace 0, and a trace without x. Real Plotly raises a clear error for unknown properties but does not check data lengths for you, so a check like this belongs in your tests; see the testing lesson.

Part 2: bins, reshaping and smoothing (Python)

Exercise 4: a histogram. Given a list of exam scores from 0 to 100, return the count in each bin of width 10 (0-9, 10-19, ..., 90-100, where 100 belongs to the last bin). Empty bins must appear with a count of 0; a histogram that skips empty bins misleads.

Exercise 5: wide to long. A table has one row per month and one column per product ({"month": "Jan", "tea": 3, "coffee": 5}). Convert it to long form, one row per month and product, with the columns month, product, units. This is melt in pandas and transform_fold in Altair; the tidy data lesson explains why charts want this shape.

Exercise 6: a rolling mean. Write rolling_mean(values, size) that returns a list the same length as the input. The first size - 1 entries are None; the rest are the mean of the last size values, rounded to 2 decimals.

Solutions 4 to 6

Python Exercises 4 to 6: bins, melt, rolling mean

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.

Check the edge cases a chart would hit: the score 100 must not create an eleventh bin (the min(...) handles it), and empty bins print a count of 0. The first bins of this data show that 40 to 49 holds one student and 50 to 59 holds one, while nobody scored 0 to 39.

Part 3: scales and ticks (JavaScript)

Exercise 7: a linear scale. Write linear(domain, range) that returns a function mapping a data value to a pixel, with an invert method. The y axis of a chart uses the range [200, 0].

Exercise 8: a band scale. Write band(keys, range, padding) returning a function from a category to the start of its slot, with a bandwidth property. Padding is the fraction of each slot left empty.

Exercise 9: nice ticks. Write niceTicks(max, wanted) returning tick values starting at 0 with a step of 1, 2 or 5 times a power of ten, that reach at least max. These three exercises rebuild what How a Chart Works Inside introduced.

Solutions 7 to 9

JS Exercises 7 to 9: scales and ticks

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

No output.

In exercise 9 the raw step for 180 and 5 ticks is 36, which is rounded up to 50, giving an axis that ends at 200. That is why charts rarely stop exactly at your maximum. Note the rounding with 1e6: repeatedly adding a step like 0.5 is exact in binary, but steps like 0.1 are not, and unrounded ticks print as 0.30000000000000004.

Part 4: judgment (JavaScript)

Exercise 10: contrast. Write contrast(hex1, hex2) returning the WCAG contrast ratio: convert each channel to linear light (c / 255, then c / 12.92 if at most 0.04045, else ((c + 0.055) / 1.055) ** 2.4), compute the luminance 0.2126 R + 0.7152 G + 0.0722 B, and return (lighter + 0.05) / (darker + 0.05). Then report whether label text passes the 4.5 minimum for normal text. See Color, Labels and Accessibility.

Exercise 11: choose a library. Write recommend(needs) that takes an object of yes or no needs and returns a library name and a reason. Use this rule set: streaming data with Python callbacks means Bokeh; a multi-page web app with callbacks means Plotly with Dash; a small dataset with several linked, declarative charts means Altair; anything else means Plotly Express, because it is the fastest way to a good interactive chart. Your answer will differ in the details, since the choice is a judgment; the aim is to make the rules explicit.

Exercise 12: the lie factor. A bar chart's axis starts at base instead of 0. Two bars show v1 and v2. Write lieFactor(v1, v2, base) as the ratio of the relative change you see (bar heights are v - base) to the relative change in the data. A value near 1 is honest.

Solutions 10 to 12

JS Exercises 10 to 12: contrast, library choice, lie factor

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

No output.

Exercise 10 shows that mid-grey text (#777777) on white fails the 4.5 test, while the blue passes easily and white text on amber also fails: a common mistake in chart labels on warm fills. For exercise 12, cutting the axis at 45 makes a 10 percent increase look like a 100 percent increase, a lie factor of 10. Bar charts must start at zero for this reason; a line chart can zoom, but should say so.

What to try next

  • Extend exercise 1 to accept an optional color field and add the color encoding.
  • Extend exercise 4 so the bin width is a parameter and the top bin is open-ended.
  • Combine exercises 3 and 7: draw the sorted totals as an SVG bar chart.
  • Rewrite your answers to 4, 5 and 6 as pandas one-liners and compare the results to your loops.
  • Read the interview questions and answer them out loud.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must a histogram show bins with a count of zero?

    An empty bin is information: nobody scored in that range. If it disappears, neighbouring bars look adjacent.
  2. 2. In the rolling mean of exercise 6, why are the first size-1 entries None?

    There are not yet size values to average. None (NaN in pandas) is drawn as a gap, which is honest.
  3. 3. White text on an amber fill scored below 4.5 in exercise 10. What does that mean?

    WCAG asks for at least 4.5:1 for normal text. Low contrast hurts many readers, not only those with color blindness.
  4. 4. A bar chart axis starts at 45 and the bars show 50 and 55. What is true?

    Bar heights are 5 and 10, so the second bar looks twice as tall, though the data grew by 10 percent.

Summary

  • A chart spec is plain data; validate it with ordinary code before you draw it.
  • Aggregation, binning, melting and rolling means are small row-in, row-out functions; handle empty bins and incomplete windows explicitly.
  • Linear and band scales plus nice ticks are the core of every axis; the y range is flipped because pixels grow downward.
  • Contrast ratios and lie factors turn "looks off" into numbers you can test.
  • Choosing a library is a judgment; write your rules down so the choice is repeatable.

Next: Data Visualization Interview Questions