Quiz: Customization Mastery
20 questions. Aim for mastery (18+). If you score below 14, revisit the relevant sections before moving to Chapter 13.
Multiple Choice (10 questions)
1. Which of the following is NOT a valid way to specify a color in matplotlib?
(a) "steelblue" (named color)
(b) "#1f77b4" (hex code)
(c) (0.12, 0.47, 0.71) (RGB tuple)
(d) "blue100" (intensity suffix)
Answer
**(d)** `"blue100"`. matplotlib accepts named colors, hex codes, RGB/RGBA tuples, and grayscale float strings (`"0.5"`). Intensity suffixes like `"blue100"` are not part of matplotlib's color specification — they are invented. The standard formats are the four covered in Section 12.1.2. The single biggest improvement most beginners can make to a default matplotlib chart is:
(a) Changing the font (b) Removing the top and right spines (c) Adding more gridlines (d) Increasing the default figsize
Answer
**(b)** Removing the top and right spines. `ax.spines["top"].set_visible(False)` and `ax.spines["right"].set_visible(False)` — two lines per chart — produce a dramatic visual improvement with no side effects. This is the first step of the Chapter 6 declutter procedure in code, and it is usually the first thing experienced matplotlib users do to any chart. The other options are useful but not as impactful as a first change.3. The plt.rc_context context manager is used for:
(a) Permanently changing matplotlib settings for the entire session (b) Temporarily applying rcParams within a specific block, reverting automatically afterward (c) Creating a new Figure (d) Switching between matplotlib backends
Answer
**(b)** Temporarily applying rcParams within a specific block, reverting automatically afterward.with plt.rc_context({"font.size": 14}):
# any matplotlib code here uses font.size = 14
pass
# outside the block, font.size is back to whatever it was before
This is useful for producing a single chart with non-default settings (for example, a dark-themed chart in an otherwise light-themed script) without polluting global state.
4. To set matplotlib's pdf.fonttype to 42 for publication-ready PDF output, you should:
(a) Install a different PDF backend
(b) Set mpl.rcParams["pdf.fonttype"] = 42 before creating your figures
(c) Pass fonttype=42 to savefig
(d) Use the SVG format instead
Answer
**(b)** Set `mpl.rcParams["pdf.fonttype"] = 42` before creating your figures. The default PDF font type in matplotlib is Type 3, which is not accepted by many journal publishing systems. Setting `pdf.fonttype` to 42 uses TrueType (Type 42) fonts, which embed correctly and are universally supported. Set this at the top of your script or in your style sheet and forget about it.5. To format a y-axis with thousand separators (e.g., 5000 displayed as "5,000"), use:
(a) ax.set_yticks(values) with formatted strings
(b) ax.yaxis.set_major_formatter(StrMethodFormatter("{x:,.0f}"))
(c) Manually set each tick label with ax.set_yticklabels
(d) Multiply the values by 0.001 before plotting
Answer
**(b)** `ax.yaxis.set_major_formatter(StrMethodFormatter("{x:,.0f}"))`. The `StrMethodFormatter` takes a Python format string (in the `str.format` syntax) and applies it to every tick label automatically. `{x:,.0f}` means "format the value with thousand separators and no decimal places." For more complex formatting, use `FuncFormatter` with a custom function.6. To create a reusable matplotlib style, the recommended approach is:
(a) Copy-paste customization code into every chart
(b) Create a .mplstyle file or a reusable Python style function
(c) Use a different plotting library
(d) Save each chart as a template
Answer
**(b)** Create a `.mplstyle` file or a reusable Python style function. Both approaches let you define customization once and apply it automatically to future charts. A `.mplstyle` file holds rcParams that affect all subsequent plots. A style function (e.g., `apply_clean_style(ax)`) applies specific customization to a specific Axes. The chapter's threshold concept is that matplotlib customization should be systematic, not ad hoc.7. For a climate chart showing temperature anomalies with a meaningful zero midpoint, the recommended colormap type is:
(a) Sequential (e.g., viridis) (b) Diverging (e.g., RdBu_r) (c) Qualitative (e.g., tab10) (d) Cyclic (e.g., twilight)
Answer
**(b)** Diverging (e.g., RdBu_r). Diverging colormaps are designed for data with a meaningful midpoint, with colors diverging in two directions away from that midpoint. Temperature anomalies have a natural midpoint (the baseline zero), with warmer on one side and cooler on the other. A sequential colormap would imply an ordered scale from low to high without emphasizing the midpoint. For the climate data, `RdBu_r` (reversed so warm is red) is the standard choice.8. The bbox_inches="tight" parameter in fig.savefig(...) does what?
(a) Makes the figure fit inside a tight box (b) Crops the saved image to the actual chart content, removing excess whitespace (c) Reduces the file size (d) Compresses the figure vertically
Answer
**(b)** Crops the saved image to the actual chart content, removing excess whitespace. Without `bbox_inches="tight"`, matplotlib sometimes saves more blank space around the chart than you want. `"tight"` tells savefig to compute the minimal bounding box that contains all the chart elements and crop to that. Combined with `dpi=300`, this is the canonical savefig call for publication-quality output.9. To place a figure-level subtitle under the main title:
(a) fig.text(0.125, 0.92, "subtitle", fontsize=11, color="gray") or fig.suptitle("Main\nSubtitle")
(b) ax.set_subtitle("subtitle")
(c) plt.subtitle("subtitle")
(d) ax.annotate("subtitle", loc="upper center")
Answer
**(a)** `fig.text(0.125, 0.92, "subtitle", fontsize=11, color="gray")` or `fig.suptitle("Main\nSubtitle")`. matplotlib does not have a built-in `set_subtitle` method. To add a subtitle, you either use `fig.text` with explicit figure-relative coordinates, use `fig.suptitle` with a multi-line string, or use `ax.text` with `transform=ax.transAxes` and axes-relative coordinates. The `fig.text` approach is the most common for standalone subtitles.10. The chapter's threshold concept says that professional matplotlib is:
(a) Faster to write than amateur matplotlib (b) Systematic — based on style sheets and reusable functions rather than ad-hoc tweaking (c) Based on the latest features of matplotlib 3.x (d) Only for publication-quality output
Answer
**(b)** Systematic — based on style sheets and reusable functions rather than ad-hoc tweaking. The shift from customizing individual charts to building a style system (style sheets, rcParams, reusable functions) is the mark of a matplotlib user who has moved past the beginner phase. The style system makes every chart consistent by default and reduces per-chart customization to near-zero for routine work.True / False (5 questions)
11. "The default matplotlib color cycle is colorblind-safe and should be used without modification."
Answer
**False.** matplotlib's default color cycle ("tab10") is *reasonable* — it is distinguishable for most types of color blindness — but it is not designed to be an optimal choice for every chart. For publication-quality work, you should specify colors explicitly based on the principles from Chapter 3 (sequential, diverging, qualitative) and verify them with colorblind simulation tools. The default is acceptable for quick exploration but not a substitute for a deliberate palette.12. "Setting ax.spines['top'].set_visible(False) is a Chapter 6 declutter operation."
Answer
**True.** This is exactly Chapter 6's "remove" step of the declutter procedure, applied to matplotlib code. The top spine is structural chart-junk (it encloses the plotting area but serves no reading function), and removing it reduces visual noise without removing any data. Combined with removing the right spine, this is the single highest-impact customization for most charts.13. "Style sheets and rcParams accomplish the same thing — applying settings globally to matplotlib charts."
Answer
**True (with a nuance).** A style sheet is a bundle of rcParams values saved as a named theme. When you call `plt.style.use("my_style")`, matplotlib reads the style sheet and applies the settings to `rcParams`. They are the same mechanism at different levels of abstraction: rcParams is the low-level global config dictionary, and style sheets are a convenient way to save and apply sets of rcParams values.14. "For publication PDF output, leaving pdf.fonttype at its default value is acceptable."
Answer
**False.** The default `pdf.fonttype` is Type 3, which is not accepted by many journal publishing systems because Type 3 fonts are not true embedded fonts and cannot be reliably rendered across different PDF viewers. You should set `mpl.rcParams["pdf.fonttype"] = 42` (Type 42 TrueType) for any PDF that will be submitted to a journal or shared with an audience that might re-render the PDF in a different environment.15. "Direct labeling of lines is always preferable to a legend."
Answer
**False.** The chapter (and Chapter 7) say direct labeling is usually preferable, but there are exceptions: dense charts with many series (where labels would overlap), charts with crossing lines (where labels would collide), and charts that are part of interactive dashboards with hover features (where the hover provides on-demand labeling). Direct labeling is the default choice, but legends remain appropriate in specific cases.Short Answer (3 questions)
16. In three to four sentences, explain the difference between global rcParams settings and a context manager (plt.rc_context). When would you use each?
Answer
**Global rcParams** (e.g., `mpl.rcParams["font.size"] = 12`) change the default settings for every chart in the rest of the session. Use them when you want consistent styling across an entire script or notebook. **Context managers** (e.g., `with plt.rc_context({"font.size": 14}):`) apply settings only within the `with` block and revert to the previous state afterward. Use them when you need non-default styling for a specific chart without affecting the rest of the session — for example, one dark-themed chart in an otherwise light-themed script. Both work; the context manager is safer when you want isolation.17. Describe the "reusable style function" pattern (e.g., apply_clean_style(ax)) and explain why the chapter recommends it as the mark of a professional matplotlib user.
Answer
A reusable style function takes an Axes (and optionally a Figure) and applies a set of customizations in one call. For example, `apply_clean_style(ax)` might remove the top and right spines, lighten the remaining spines, add light gridlines, and set tick parameters. By encapsulating the customization logic, you avoid repeating the same code in every chart, and you can update your house style in one place. The chapter recommends this pattern because it reduces per-chart customization to near-zero while maintaining consistency — the mark of a professional who has built a style system rather than tweaking each chart individually.18. Explain the difference between a sequential, a diverging, and a qualitative colormap. Give one matplotlib colormap name for each category and state when to use it.
Answer
A **sequential** colormap runs from low to high in a single direction, with darker (or lighter) colors for higher values. Use for ordered data without a meaningful midpoint — for example, count data, intensity, or time. matplotlib's default sequential colormap is `"viridis"`. A **diverging** colormap runs from one color through a neutral midpoint (usually white) to a contrasting color. Use for data with a meaningful midpoint — anomalies, differences from baseline, gain versus loss. Example: `"RdBu_r"`. A **qualitative** colormap uses distinct colors with no ordered relationship between them. Use for categorical data where categories have no inherent order — product lines, country names, experimental conditions. Example: `"tab10"` or `"Set2"`.Applied Scenarios (2 questions)
19. You have written the following matplotlib code for a climate chart. Apply the Chapter 12 customization techniques to transform it into a publication-ready chart. Describe at least six specific changes you would make.
fig, ax = plt.subplots()
ax.plot(climate["year"], climate["anomaly"])
ax.set_title("Climate Data")
fig.savefig("chart.png")
Answer
**Changes:** 1. **Set an explicit figsize** (`figsize=(12, 4)`) for a wide time-series aspect ratio. 2. **Set an explicit color and linewidth** (`color="#d62728", linewidth=1.5`) instead of accepting defaults. 3. **Remove the top and right spines** with `ax.spines["top"].set_visible(False)` and `ax.spines["right"].set_visible(False)`. 4. **Lighten the remaining spines** to gray with `ax.spines["left"].set_color("gray")` etc. 5. **Rewrite the title as an action title** with a specific finding (e.g., "Global Temperatures Have Risen 1.2°C Since 1900") and left-align it with `loc="left", fontweight="semibold", pad=12`. 6. **Add an action subtitle** with `fig.text(0.125, 0.91, "NASA GISS analysis", fontsize=11, color="gray")`. 7. **Add axis labels with units** — specifically `ax.set_ylabel("Temperature Anomaly (°C)")`. 8. **Add annotations** on the 2016 and 2023 record years using `ax.annotate(...)`. 9. **Add a horizontal reference line** at zero with `ax.axhline(0, color="gray", linewidth=0.8, linestyle="--")`. 10. **Add light horizontal gridlines** with `ax.grid(True, axis="y", color="#cccccc", linewidth=0.5, alpha=0.6)` and `ax.set_axisbelow(True)`. 11. **Add an on-image source attribution** with `fig.text(0.125, 0.02, "Source: NASA GISS", fontsize=8, color="gray", style="italic")`. 12. **Save at publication resolution** with `dpi=300, bbox_inches="tight"`. Any six or more of these changes would be defensible. The full transformation is shown in Section 12.13 of the chapter.20. You are preparing charts for three different contexts: (a) a scientific paper for a traditional journal, (b) a blog post on your personal website, and (c) a slide deck for an internal company presentation. Describe how your matplotlib style would differ across the three contexts, and justify each difference.
Answer
**(a) Scientific paper:** - **Fonts**: Serif (Times New Roman or similar) for consistency with scientific journal conventions. Smaller size (8-10pt). - **Colors**: Conservative, often grayscale or two-tone. Diverging palettes used for anomaly data, sequential for ordered data. - **Layout**: Single-column figsize like `(3.5, 2.5)` or two-column `(7, 5)`, matching the journal's column width. - **Spines**: Often all four spines visible, matching traditional scientific convention. Minimal gridlines. - **Resolution**: 300 DPI PDF or TIFF with Type 42 fonts for journal submission. **(b) Blog post:** - **Fonts**: Sans-serif (Inter, Source Sans Pro). Medium size (11-12pt). - **Colors**: More use of accent color for emphasis. Action titles in bold. - **Layout**: Wider aspect ratios for desktop screens (`(12, 5)` typical). - **Spines**: Top and right removed for a modern look. Light gridlines. - **Resolution**: PNG at 150 DPI for web display; SVG for vector clarity when zoomed. **(c) Slide deck:** - **Fonts**: Sans-serif, large size (14-18pt or bigger for titles). - **Colors**: High contrast. Dark background with bright accent colors works well in dimmed conference rooms. - **Layout**: Wide aspect ratio (`(14, 6)` or similar) to match slide proportions. Minimal text so the audience can read at a glance. - **Spines**: Minimized or removed. No gridlines. - **Resolution**: 150 DPI PNG (no need for higher since slides are projected). **Justifications:** Each context has different constraints: audience expectations, display medium, attention budget, and reproducibility requirements. The scientific paper prioritizes rigor and convention. The blog post prioritizes visual appeal and readability on diverse devices. The slide deck prioritizes legibility in a large room with brief attention windows. The same underlying data and chart type can serve all three audiences, but the visual styling has to match each context to be effective. Build a separate style function for each context, and switch between them based on which output you need.Review your results against the mastery thresholds. If you scored below 14, revisit Sections 12.1-12.10 — each covers one aspect of customization, and the concepts build on each other. Chapter 13 moves on to multi-panel layouts and GridSpec, where the customization skills from this chapter combine with the composition principles from Chapter 8.