Data Analysis / Intermediate: Relationships and Uncertainty / Lesson 9
Visualization Design, Bins, and Uncertainty
Choose a graphic that exposes the comparison, preserves measurement meaning, and states uncertainty without turning visual styling into evidence.
On this page
Lesson goals
- Match a chart to the analytical task.
- Explain axes, histogram bins, and units.
- Label variability and uncertainty precisely.
Choose the comparison before choosing the chart
Use bars for category comparisons, lines for a meaningful ordered progression such as time, a histogram for a numeric distribution, and a scatter plot for paired observations. A connecting line asserts an order and visual continuity; it can invent a relationship when categories are arbitrary. Start with the question and the data grain, not the most elaborate available chart type.
A useful title states the measured outcome, population, and period rather than announcing a conclusion the design cannot support. Put units in axis labels and explain filters, denominators, and missing values. The examples use synthetic values and Matplotlib3.6.3 with Agg, so they render without a desktop or external service and close every figure after use.
Treat scales as part of the argument
Bar length encodes magnitude, so a nonzero baseline can exaggerate a modest difference. The first program places rates20 and30 on a zero-to-fifty scale and labels them as percentages. Its printed checks verify the intended heights and limits, not whether the two groups differ statistically. The chart contains no sampling model and therefore no inferential evidence by itself.
A zero baseline is not compulsory for every line or scatter plot; choose a justified range and disclose it. Logarithmic scales encode ratios and cannot display ordinary zero or negative values. Do not silently drop those observations to make a log plot work. Compare like units and align scales across panels when readers are meant to compare their apparent variation.
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(4, 3))
try:
bars = ax.bar(["A", "B"], [20, 30])
ax.set_ylim(0, 50)
ax.set_ylabel("Completion rate (%)")
ax.set_title("Synthetic groups, defined period")
fig.tight_layout()
fig.canvas.draw()
print("bars", [int(bar.get_height()) for bar in bars])
print("ylim", *ax.get_ylim())
finally:
plt.close(fig)
bars [20, 30]
ylim 0.0 50.0
The two heights are20 and30, with a0..50 vertical scale. Drawing on Agg validates rendering without opening a GUI.
Make histogram boundaries and normalization visible
A histogram groups numeric values into intervals. Bin width and origin can reveal or conceal apparent modes, so inspect more than one defensible specification rather than choosing the prettiest. For Matplotlib's underlying histogram convention, bins are left-closed/right-open except that the last includes its right endpoint. The second program deliberately places observations exactly on boundaries to make this rule testable.
The bins0..2 and2..4 contain two and three values respectively, because2 belongs in the second and4 is included at the final endpoint. With unequal widths, a count-height plot can mislead about area; use an appropriately labeled frequency density or probability density when area should represent quantity. density=True normalizes area, not a promise that bar heights sum to one.
import io
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(4, 3))
try:
counts, edges, _ = ax.hist([0, 1, 2, 3, 4], bins=[0, 2, 4])
ax.set_xlabel("Synthetic measurement (units)")
ax.set_ylabel("Observation count")
fig.tight_layout()
print("counts", counts.astype(int).tolist())
print("edges", edges.astype(int).tolist())
with io.BytesIO() as image:
fig.savefig(image, format="png")
print("png", image.getvalue().startswith(b"\x89PNG\r\n\x1a\n"))
finally:
plt.close(fig)
counts [2, 3]
edges [0, 2, 4]
png True
Values0 and1 enter the first bin;2,3,and4 enter the second. A PNG is generated in memory, inspected, and discarded.
Name what an interval or ribbon represents
Error bars can represent standard deviation, standard error, a confidence interval, or another range; they are not interchangeable. State the method, confidence level where relevant, observation unit, and sample size. A narrow interval under a wrong independence assumption can be precise-looking and invalid. A chart must not manufacture uncertainty from visual spacing or use a decorative ribbon without a defined calculation.
Separate variability among observations from uncertainty about an estimated mean. Show raw or distributional information when feasible, especially for small or uneven groups. Overlapping confidence intervals are not a general test of no difference, and non-overlap is not a causal argument. The reader needs the estimate's target and the assumptions behind its interval, not only a color-coded impression.
Verify the graphic and its accessible explanation
Audit plotted values against the table, check category ordering and axis units, and include a text summary with the main comparison and limitations. Do not rely on color alone; distinguish series through labels, markers, or line styles where useful. A table or written description should remain available when a reader cannot inspect the image. Avoid decorative3D effects that distort size judgments.
For publication, preserve the code, data definition, bin or axis choices, and output artifact under a reproducible process. Close figures to avoid retaining memory during batch rendering. The tiny examples validate mechanics and known values only; they do not establish that an unlabeled real dataset has the same quality or that a visual difference justifies a decision.
Common errors and fixes
A small change looks enormous in a bar chart.
- Why it happens
- The magnitude-encoding bars start at a truncated baseline.
- How to fix it
- Use a justified zero baseline or a different clearly explained encoding.
- Prevent it next time
- Review plotted limits and labels against the intended comparison.
A boundary value is counted in the wrong bin.
- Why it happens
- The bin endpoint convention was assumed rather than specified.
- How to fix it
- Declare edges and test values at each boundary.
- Prevent it next time
- Preserve bin definitions with the analysis.
An error bar is described as uncertainty without a method.
- Why it happens
- Variability, standard error, and confidence limits were conflated.
- How to fix it
- Label the quantity and calculate it under stated assumptions.
- Prevent it next time
- Require an interval definition in every figure specification.
Check your understanding
1. Using bins[0,2,4], place0,1,2,3,4 under the documented histogram convention.
Show worked solution
The first bin contains0 and1, and the final bin contains2,3,and4. Thus the counts are2 and3. The last right edge is included; changing edges changes the display, so retain them in the reproducibility record.
2. A line chart shows monthly averages with ribbons but no legend explaining the ribbons. What information is missing?
Show worked solution
State whether the ribbon shows SD, SE, a confidence interval, or another range, together with its method, sample unit, sample size, and any independence assumptions. Explain missing months and whether connected segments imply interpolation. Color alone cannot supply this analytical definition.
Key takeaways
- Chart form should follow the question and grain.
- Axes, bin rules, and uncertainty definitions are analytical choices.
- A reproducible graphic includes values, method, labels, and limitations.