Sign in

Visualization

Exploratory data visualization

The three basic charts of exploratory analysis (line, bar and scatter) drawn as SVG, plus a numeric reading of trend, outliers and peaks.

Overview

A chart turns numbers into positions so the eye can find patterns that a table hides. Three charts cover most first looks. A line chart shows a value along an ordered axis, usually time, and reveals trends and cycles. A bar chart compares one value across categories. A scatter chart puts two numeric variables on the two axes and shows whether they are related. Drawing any of them comes down to one step: a rule that maps a data value to a pixel position. The folder is named after Matplotlib, but nothing here imports it. The charts are plain SVG text built with NumPy, meant for quick looks and not for publication, with no legends, multiple series or date axes. The detect_patterns method returns as numbers what you would read off the picture.

A short history

William Playfair introduced the line chart and the bar chart in his Commercial and Political Atlas of 1786 to show English trade over time. The scatter plot is usually credited to John Herschel, who used one in 1833 to study the orbits of double stars. John Tukey's work in the 1970s made plotting the centre of exploratory analysis, and John Hunter's Matplotlib, first released in 2003, became the standard plotting library for Python.

How it works

  1. Find the range of the data on each axis and choose tick values at round numbers with nice_ticks.
  2. Map each data value to a pixel position with x_pixels and y_pixels. The vertical map is flipped, because SVG counts pixels downward from the top.
  3. For line, join the points in the order given. For scatter, draw a dot at each point, with the least-squares line when trend_line is true.
  4. For bar, draw one rectangle per label from zero to its value. Negative values hang below zero.
  5. Add the axes, tick labels and title, and return the whole SVG document as a string.
  6. For a numeric reading, detect_patterns fits a least-squares line and reports its slope, the correlation and the direction: increasing, decreasing or flat.
  7. It then lists outliers, the points whose distance from the line is unusually large on a robust scale, and the peaks and troughs, which are local highs and lows.

Watch out for

  • Bars here always start at zero, which is correct because bar length encodes the value. A line or scatter axis covers only the data range, so a small change can look steep.
  • A line chart joins points in the order given. If the x values are not sorted, the line doubles back and suggests a pattern that is not there.
  • Peaks are plain local maxima, so a noisy series reports a peak at every wiggle. Smooth the series first.
  • The trend line and the correlation describe a straight-line relation. A strong curved relation can be reported as flat.
  • With many points a scatter chart overplots: dots pile on top of each other and the dense regions look no darker than sparse ones.

Use cases

When to use it

A line chart for change over time, a bar chart to compare categories, a scatter chart to check a relation before computing a correlation or fitting a model. Use detect_patterns to scan many series for trends or anomalies as numbers.

In industry

Business reporting
Analysts plot revenue as a line over months and compare regions with bars, the same two forms Playfair used for trade figures.
Science and engineering
Experimenters draw a scatter plot of two measured quantities first, to see whether the relationship is linear and whether any run is an outlier.
Operations monitoring
Dashboards chart request rates and error counts over time so that peaks and sudden changes are visible at once.

Choosing it: what must hold

  • A line chart needs an ordered axis such as time, a bar chart needs categories, and a scatter plot needs two numeric variables.
  • Few enough series or categories to stay readable, typically under a dozen.
  • Bar axes that start at zero, so that bar lengths compare honestly.

When to choose something else

IfUse instead
You want to compare distributions across groupsBox plots
You want the shape of one numeric variableA histogram or density estimate from distribution analysis
There are too many points for a scatter plot to be readableA binned density plot or a random sample of the points

Math foundations

  1. Data to horizontal pixel

    px=g+x−xloxhi−xlo (W−2g)p_x = g + \frac{x - x_{\text{lo}}}{x_{\text{hi}} - x_{\text{lo}}} \, (W - 2g)

    A linear scale. The lowest axis value lands at the left margin, the highest at the right margin, and everything else in proportion.

  2. Data to vertical pixel

    py=H−g−y−yloyhi−ylo (H−2g)p_y = H - g - \frac{y - y_{\text{lo}}}{y_{\text{hi}} - y_{\text{lo}}} \, (H - 2g)

    The same scale, flipped. SVG measures down from the top, so a larger data value must get a smaller pixel number.

  3. Least-squares line

    b=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2,a=yˉ−b xˉb = \frac{\sum_{i} (x_i - \bar{x})(y_i - \bar{y})}{\sum_{i} (x_i - \bar{x})^{2}}, \qquad a = \bar{y} - b\,\bar{x}

    The line y=a+bxy = a + bx that makes the sum of squared vertical gaps to the points as small as possible. The slope bb is the change in yy per unit of xx.

  4. Correlation

    r=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2 ∑i(yi−yˉ)2r = \frac{\sum_{i} (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_{i} (x_i - \bar{x})^{2}} \, \sqrt{\sum_{i} (y_i - \bar{y})^{2}}}

    How tightly the points follow a line, from -1 to 1. The relation is called flat when ∣r∣|r| is below the configured flat_r.

  5. Robust outlier rule

    ∣ei−med⁡(e)∣>z⋅1.4826⋅med⁡(∣e−med⁡(e)∣)\big| e_i - \operatorname{med}(e) \big| > z \cdot 1.4826 \cdot \operatorname{med}\big( |e - \operatorname{med}(e)| \big)

    Each residual eie_i is compared with a spread built from medians, the median absolute deviation. The factor 1.4826 makes it equal the standard deviation for normal data. Medians keep the outliers themselves from inflating the yardstick.

Symbols

x,yx, y
a data value on the horizontal and on the vertical axis
xlo,xhix_{\text{lo}}, x_{\text{hi}}
lowest and highest value of the horizontal axis (likewise for y)
W,HW, H
chart width and height in pixels
gg
the margin around the plot area in pixels
px,pyp_x, p_y
pixel position, measured from the left and from the top
a,ba, b
intercept and slope of the least-squares line
xˉ,yˉ\bar{x}, \bar{y}
the means of the x and y values
rr
Pearson correlation of x and y
eie_i
residual of point i: its y value minus the line's value
zz
the outlier threshold (outlier_z, default 3.0)
med⁡\operatorname{med}
the median

Worked by hand

A chart is 640 pixels wide and 400 high with a margin of 50. Both axes run from 0 to 100. Where is the point (25, 25) drawn? Then fit a line to the points (1, 2), (2, 4), (3, 9).

px=50+25−0100−0×(640−100)=50+0.25×540=185p_x = 50 + \frac{25 - 0}{100 - 0} \times (640 - 100) = 50 + 0.25 \times 540 = 185
py=400−50−25−0100−0×(400−100)=350−75=275p_y = 400 - 50 - \frac{25 - 0}{100 - 0} \times (400 - 100) = 350 - 75 = 275
xˉ=2,yˉ=5,b=(−1)(−3)+(0)(−1)+(1)(4)1+0+1=72=3.5\bar{x} = 2, \quad \bar{y} = 5, \quad b = \frac{(-1)(-3) + (0)(-1) + (1)(4)}{1 + 0 + 1} = \frac{7}{2} = 3.5
a=5−3.5×2=−2a = 5 - 3.5 \times 2 = -2

The point is drawn 185 pixels from the left and 275 from the top, a quarter of the way along each axis. The fitted line is y=−2+3.5xy = -2 + 3.5x.

Visual example

Loading the example.

Try this

  • Drag the high value at x = 7 down toward the line and watch it stop being flagged as an outlier.
  • Switch between line, scatter and bar and notice which pattern each chart makes easy to see.
  • Lower the outlier threshold z to 1 and see how many ordinary points get flagged.

Code sample

import numpy as np
from impl import Visualization, nice_ticks
from config import VisualizationConfig

rng = np.random.default_rng(0)
x = np.arange(40.0)
y = 0.5 * x + rng.normal(0, 1.0, size=40)
y[17] += 25.0

viz = Visualization(VisualizationConfig(title="Demo", width=640, height=400))
open("line.svg", "w").write(viz.line(x, y))
open("scatter.svg", "w").write(viz.scatter(x, y, trend_line=True))
open("bar.svg", "w").write(viz.bar(["north", "south", "east"], [12, 30, 21]))
patterns = viz.detect_patterns(x, y)
print(patterns["direction"], round(patterns["slope"], 2), patterns["outliers"])   # increasing 0.5 [17]
print(nice_ticks(0.13, 0.87))                                                     # [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
Read the implementation (200 lines)
"""Visualization without a plotting library: line, bar and scatter charts as SVG, plus pattern detection.

NumPy and the standard library only. Each chart method returns a complete SVG document as a string, which a
browser, a notebook or an image viewer can show. `detect_patterns` computes what the eye looks for in such a
chart: the direction and strength of the trend, points far off the trend line, and peaks and troughs.
"""
from __future__ import annotations

import math
from xml.sax.saxutils import escape

import numpy as np

try:
    from .config import VisualizationConfig
except ImportError:  # run from the template's own folder
    from config import VisualizationConfig


def _nice(value: float, round_it: bool) -> float:
    """Closest "nice" number (1, 2, 5 or 10 times a power of ten) to value; rounded, or the next one up."""
    exponent = math.floor(math.log10(value))
    fraction = value / 10.0**exponent
    if round_it:
        nice = 1.0 if fraction < 1.5 else 2.0 if fraction < 3.0 else 5.0 if fraction < 7.0 else 10.0
    else:
        nice = 1.0 if fraction <= 1.0 else 2.0 if fraction <= 2.0 else 5.0 if fraction <= 5.0 else 10.0
    return nice * 10.0**exponent


def nice_ticks(low: float, high: float, n: int = 5) -> list[float]:
    """Evenly spaced tick values at round numbers that cover [low, high] (Heckbert's "nice numbers").

    n is the approximate number of ticks wanted. The first tick is <= low and the last is >= high.
    """
    if not (math.isfinite(low) and math.isfinite(high)):
        raise ValueError("axis limits must be finite")
    if low > high:
        low, high = high, low
    if low == high:
        low, high = low - 0.5, high + 0.5
    step = _nice(_nice(high - low, False) / (n - 1), True)
    first = math.floor(low / step + 1e-9)
    last = math.ceil(high / step - 1e-9)
    digits = max(0, -math.floor(math.log10(step))) + 2
    return [round(k * step, digits) for k in range(first, last + 1)]


class Visualization:
    """Draws line, bar and scatter charts as SVG and detects simple patterns in x, y data."""

    def __init__(self, config: VisualizationConfig | None = None) -> None:
        self.config = config or VisualizationConfig()

    # ---- coordinates ---------------------------------------------------------------------------------------
    def x_pixels(self, values, low: float, high: float) -> np.ndarray:
        """Horizontal pixel positions of data values when the axis runs from low (left) to high (right)."""
        c = self.config
        return c.margin + (np.asarray(values, dtype=float) - low) / (high - low) * (c.width - 2 * c.margin)

    def y_pixels(self, values, low: float, high: float) -> np.ndarray:
        """Vertical pixel positions of data values; SVG y grows downward, so `high` maps to the top."""
        c = self.config
        return c.height - c.margin - (np.asarray(values, dtype=float) - low) / (high - low) * (c.height - 2 * c.margin)

    @staticmethod
    def _xy(x, y) -> tuple[np.ndarray, np.ndarray]:
        y = np.asarray(y, dtype=float).ravel()
        x = np.arange(y.size, dtype=float) if x is None else np.asarray(x, dtype=float).ravel()
        if x.size != y.size:
            raise ValueError(f"x and y must have the same length, got {x.size} and {y.size}")
        if x.size == 0:
            raise ValueError("there is nothing to draw")
        if not (np.isfinite(x).all() and np.isfinite(y).all()):
            raise ValueError("x and y must be finite; drop missing values first")
        return x, y

    def _frame(self, y_ticks: list[float], x_ticks: list[float] | None) -> list[str]:
        """Opening tags, background, title, both axes and their tick labels."""
        c = self.config
        left, right, top, bottom = c.margin, c.width - c.margin, c.margin, c.height - c.margin
        parts = [
            f'<svg xmlns="http://www.w3.org/2000/svg" width="{c.width}" height="{c.height}" viewBox="0 0 {c.width} {c.height}">',
            f'<rect class="background" x="0" y="0" width="{c.width}" height="{c.height}" fill="white"/>',
            f'<line class="axis" x1="{left}" y1="{bottom}" x2="{right}" y2="{bottom}" stroke="black"/>',
            f'<line class="axis" x1="{left}" y1="{top}" x2="{left}" y2="{bottom}" stroke="black"/>',
        ]
        if c.title:
            parts.append(f'<text class="title" x="{c.width / 2}" y="{top / 2 + 5}" text-anchor="middle" font-size="15">{escape(c.title)}</text>')
        for tick, pixel in zip(y_ticks, self.y_pixels(y_ticks, y_ticks[0], y_ticks[-1])):
            parts.append(f'<line class="grid" x1="{left}" y1="{pixel:.2f}" x2="{right}" y2="{pixel:.2f}" stroke="#dddddd"/>')
            parts.append(f'<text class="y-tick" x="{left - 6}" y="{pixel + 4:.2f}" text-anchor="end" font-size="11">{tick:g}</text>')
        if x_ticks is not None:
            for tick, pixel in zip(x_ticks, self.x_pixels(x_ticks, x_ticks[0], x_ticks[-1])):
                parts.append(f'<text class="x-tick" x="{pixel:.2f}" y="{bottom + 16}" text-anchor="middle" font-size="11">{tick:g}</text>')
        return parts

    # ---- charts --------------------------------------------------------------------------------------------
    def line(self, x, y) -> str:
        """Line chart. y: shape (n,). x: shape (n,) or None for 0, 1, 2, ... Points are joined in the order given."""
        x, y = self._xy(x, y)
        x_ticks = nice_ticks(float(x.min()), float(x.max()), self.config.n_ticks)
        y_ticks = nice_ticks(float(y.min()), float(y.max()), self.config.n_ticks)
        px = self.x_pixels(x, x_ticks[0], x_ticks[-1])
        py = self.y_pixels(y, y_ticks[0], y_ticks[-1])
        points = " ".join(f"{a:.2f},{b:.2f}" for a, b in zip(px, py))
        parts = self._frame(y_ticks, x_ticks)
        parts.append(f'<polyline class="line" points="{points}" fill="none" stroke="{self.config.color}" stroke-width="2"/>')
        parts.append("</svg>")
        return "\n".join(parts)

    def scatter(self, x, y, trend_line: bool = False) -> str:
        """Scatter chart of points (x[i], y[i]), shapes (n,). trend_line=True adds the least-squares line."""
        x, y = self._xy(x, y)
        x_ticks = nice_ticks(float(x.min()), float(x.max()), self.config.n_ticks)
        y_ticks = nice_ticks(float(y.min()), float(y.max()), self.config.n_ticks)
        px = self.x_pixels(x, x_ticks[0], x_ticks[-1])
        py = self.y_pixels(y, y_ticks[0], y_ticks[-1])
        parts = self._frame(y_ticks, x_ticks)
        for a, b in zip(px, py):
            parts.append(f'<circle class="point" cx="{a:.2f}" cy="{b:.2f}" r="3" fill="{self.config.color}" fill-opacity="0.7"/>')
        if trend_line and x.size >= 2 and np.ptp(x) > 0:
            slope, intercept = np.polyfit(x, y, 1)
            ends = np.array([x.min(), x.max()])
            ex = self.x_pixels(ends, x_ticks[0], x_ticks[-1])
            ey = self.y_pixels(intercept + slope * ends, y_ticks[0], y_ticks[-1])
            parts.append(
                f'<line class="trend" x1="{ex[0]:.2f}" y1="{ey[0]:.2f}" x2="{ex[1]:.2f}" y2="{ey[1]:.2f}" '
                f'stroke="#d62728" stroke-width="2"/>'
            )
        parts.append("</svg>")
        return "\n".join(parts)

    def bar(self, labels, values) -> str:
        """Bar chart: one bar per label. labels: n names. values: shape (n,). Bars start at zero; negative values hang below it."""
        values = np.asarray(values, dtype=float).ravel()
        labels = [str(label) for label in labels]
        if len(labels) != values.size or values.size == 0:
            raise ValueError("labels and values must have the same non-zero length")
        if not np.isfinite(values).all():
            raise ValueError("values must be finite")
        c = self.config
        y_ticks = nice_ticks(min(0.0, float(values.min())), max(0.0, float(values.max())), c.n_ticks)
        low, high = y_ticks[0], y_ticks[-1]
        zero = float(self.y_pixels(0.0, low, high))
        slot = (c.width - 2 * c.margin) / values.size
        parts = self._frame(y_ticks, None)
        for index, (label, value) in enumerate(zip(labels, values)):
            top = float(self.y_pixels(value, low, high))
            left = c.margin + slot * (index + 0.15)
            parts.append(
                f'<rect class="bar" x="{left:.2f}" y="{min(top, zero):.4f}" width="{slot * 0.7:.2f}" '
                f'height="{abs(zero - top):.4f}" fill="{c.color}"/>'
            )
            parts.append(
                f'<text class="label" x="{left + slot * 0.35:.2f}" y="{c.height - c.margin + 16}" text-anchor="middle" '
                f'font-size="11">{escape(label)}</text>'
            )
        parts.append("</svg>")
        return "\n".join(parts)

    # ---- pattern detection ---------------------------------------------------------------------------------
    def detect_patterns(self, x, y) -> dict:
        """The patterns a line or scatter chart is read for.

        x: shape (n,) or None for 0, 1, 2, ...; y: shape (n,), n >= 3.
        Returns {"slope", "intercept" (least-squares line y = intercept + slope * x), "r" (Pearson
        correlation), "direction" ("increasing", "decreasing" or "flat", flat when |r| < config.flat_r),
        "outliers" (indices of points whose residual from the line is more than config.outlier_z robust
        standard deviations from the median residual; the robust standard deviation is 1.4826 * MAD),
        "peaks" and "troughs" (indices of interior local maxima and minima of y in the order given)}.
        """
        x, y = self._xy(x, y)
        if x.size < 3:
            raise ValueError("at least three points are needed")
        if np.ptp(x) == 0:
            raise ValueError("x is constant, so there is no relation to describe")
        slope, intercept = (float(v) for v in np.polyfit(x, y, 1))
        r = float(np.corrcoef(x, y)[0, 1]) if np.ptp(y) > 0 else 0.0
        direction = "flat" if abs(r) < self.config.flat_r else ("increasing" if slope > 0 else "decreasing")
        residual = y - (intercept + slope * x)
        centre = float(np.median(residual))
        spread = 1.4826 * float(np.median(np.abs(residual - centre)))
        tolerance = 1e-9 * max(1.0, float(np.abs(y).max()))
        if spread > tolerance:
            outliers = np.flatnonzero(np.abs(residual - centre) > self.config.outlier_z * spread)
        else:  # more than half the points sit exactly on the line: anything off it stands out
            outliers = np.flatnonzero(np.abs(residual - centre) > tolerance)
        inner = np.arange(1, y.size - 1)
        peaks = inner[(y[inner] > y[inner - 1]) & (y[inner] >= y[inner + 1])]
        troughs = inner[(y[inner] < y[inner - 1]) & (y[inner] <= y[inner + 1])]
        return {
            "slope": slope,
            "intercept": intercept,
            "r": r,
            "direction": direction,
            "outliers": outliers.tolist(),
            "peaks": peaks.tolist(),
            "troughs": troughs.tolist(),
        }
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Make 40 points on the line y=0.5xy = 0.5x plus noise and add 25 to one of them, as in the template's README. Write the results of Visualization().line, scatter with trend_line=True and bar to SVG files and open them. Then call detect_patterns and check that its slope, direction and outliers match what you see. Call nice_ticks(0.13, 0.87) and explain the ticks it returns.

Check on learning

  1. Why must a bar chart's axis start at zero while a line chart's axis may start anywhere?
    A way to think about it

    Ask what the eye compares in each chart. For bars it is length, for lines it is position and slope.

  2. The outlier rule uses the median absolute deviation and not the standard deviation of the residuals. What would go wrong with the standard deviation when one point is far off the line?
    A way to think about it

    The far point enters the standard deviation squared, which widens the yardstick it is then measured against.

  3. detect_patterns reports the direction flat for points that lie on a clear U-shaped curve. Is that a bug, and what would you look at next?
    A way to think about it

    Slope and rr summarise a straight line. Look at the scatter chart itself and at the peaks and troughs.

  4. The same series is drawn with the y axis from 0 to 100 and from 49 to 51. One looks flat, the other dramatic. Which is honest?
    A way to think about it

    Neither axis is wrong by itself. Decide what size of change matters for the question, and choose the range that shows that size fairly.

  5. Why does nice_ticks return ticks from 0.0 to 1.0 for data between 0.13 and 0.87, instead of starting and ending at the data's own limits?
    A way to think about it

    Think about how a reader estimates a value between two ticks, and how hard that is with ticks at 0.13, 0.315, 0.5.