Try 'magnetic button'
View code

Number 75: Slope chart for before and after

Specification

Catalogue
No. 75 of 110
Interaction
Hover, Press
Element
Chart, Tabs
Preview
Live component
Imports
react 19.3.1, @number-flow/react 0.6.2, framer-motion 12.40.0
Added

Notes

Two axes, before and after, with a line for each channel. The lines draw in, each value carries its move in rank (+2, -1), and switching region slides every line to its new slope. Pointing at a line picks it out.

The honest way to show a change in a case study ("conversion by channel, Q1 to Q2"): one glance says what rose, what fell and what overtook what, which two bar charts side by side never do.

One line is picked out in the stage accent and the rest are grey, so identity rides on the labels beside each line, never on colour alone. Labels are spread apart so none overlap, staying as close to their line as they can. Lines draw in over 600ms cubic-bezier(.16, 1, .3, 1) on the entry page; a change of region moves both ends of every line on a 0.4s spring with no bounce. Each line has a 16px hover target. A hidden table holds the same figures for screen readers. Instant under reduced motion.

The figures are sample content.

Code

React and plain CSS
"use client";

import { useEffect, useRef, useState } from "react";
import { animate } from "framer-motion";
import type { LivePreviewProps } from "@/components/live/types";
import { physicalSpring } from "@/components/pieces/kit/physical-spring";
import { useSafeReducedMotion } from "@/components/pieces/kit/use-safe-reduced-motion";
import { radioArrows } from "@/components/pieces/shared";
import { useStageMode } from "@/components/pieces/stage/mode";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./slope-chart.css";

type Region = "americas" | "europe" | "apac";
type Row = { channel: string; before: number; after: number };

const CHANNELS = ["Email", "Search", "Social", "Referral", "Direct"] as const;
const DATA: Record<Region, Record<(typeof CHANNELS)[number], [number, number]>> = {
  americas: { Email: [2.1, 3.4], Search: [3.2, 3.5], Social: [1.4, 1.2], Referral: [2.6, 2.4], Direct: [1.8, 2.0] },
  europe: { Email: [1.9, 2.2], Search: [2.8, 3.6], Social: [1.1, 1.6], Referral: [3.0, 2.7], Direct: [2.4, 2.3] },
  apac: { Email: [1.2, 2.6], Search: [2.2, 2.4], Social: [2.0, 3.1], Referral: [1.6, 1.4], Direct: [2.7, 2.2] },
};
const REGIONS: { id: Region; label: string }[] = [
  { id: "americas", label: "Americas" },
  { id: "europe", label: "Europe" },
  { id: "apac", label: "Asia Pacific" },
];

const W = 400;
const H = 230;
const X0 = 70;
const X1 = 250;
const TOP = 26;
const BOTTOM = 210;
const LO = 0.8;
const HI = 3.8;
const LABEL_GAP = 17;
const SETTLE = physicalSpring(0.4);

const y = (v: number) => BOTTOM - ((v - LO) / (HI - LO)) * (BOTTOM - TOP);
const pct = (v: number) => `${v.toFixed(1)}%`;

function rows(region: Region): Row[] {
  return CHANNELS.map((c) => ({ channel: c, before: DATA[region][c][0], after: DATA[region][c][1] }));
}

/** Rank by value, 1 for the highest. */
function ranks(values: number[]): number[] {
  const order = [...values.keys()].sort((a, b) => values[b]! - values[a]!);
  const r = new Array<number>(values.length);
  order.forEach((idx, i) => (r[idx] = i + 1));
  return r;
}

/** Spreads label positions apart so none overlap, keeping each as close to its line as it can. */
function spread(ys: number[]): number[] {
  const idx = [...ys.keys()].sort((a, b) => ys[a]! - ys[b]!);
  const out = [...ys];
  for (let k = 1; k < idx.length; k++) {
    const prev = out[idx[k - 1]!]!;
    if (out[idx[k]!]! - prev < LABEL_GAP) out[idx[k]!] = prev + LABEL_GAP;
  }
  const over = Math.max(0, out[idx[idx.length - 1]!]! - (BOTTOM + 6));
  return out.map((v) => v - over);
}

function SlopeDemo() {
  const reduce = useSafeReducedMotion();
  const { context } = useStageMode();
  const [region, setRegion] = useState<Region>("americas");
  const [hot, setHot] = useState<string | null>(null);
  const [shown, setShown] = useState<Row[]>(() => rows("americas"));
  const current = useRef(shown);
  // Lines draw in once on the entry page; a resting card shows them drawn.
  const [drawn, setDrawn] = useState(context === "card" || reduce);

  useEffect(() => {
    const id = requestAnimationFrame(() => setDrawn(true));
    return () => cancelAnimationFrame(id);
  }, []);

  useEffect(() => {
    const from = current.current;
    const to = rows(region);
    // Every line slides from its old slope to its new one.
    const run = animate(0, 1, {
      ...(reduce ? { duration: 0 } : SETTLE),
      onUpdate: (t) => {
        const next = to.map((r, i) => ({ channel: r.channel, before: from[i]!.before + (r.before - from[i]!.before) * t, after: from[i]!.after + (r.after - from[i]!.after) * t }));
        current.current = next;
        setShown(next);
      },
    });
    return () => run.stop();
  }, [region, reduce]);

  const target = rows(region);
  const rb = ranks(target.map((r) => r.before));
  const ra = ranks(target.map((r) => r.after));
  const focus = hot ?? "Email";
  const leftY = spread(shown.map((r) => y(r.before)));
  const rightY = spread(shown.map((r) => y(r.after)));

  return (
    <div className="dm sl">
      <div className="sl-regions" role="radiogroup" aria-label="Region" onKeyDown={radioArrows}>
        {REGIONS.map((r) => (
          <button key={r.id} type="button" role="radio" aria-checked={region === r.id} tabIndex={region === r.id ? 0 : -1} className="sl-region" onClick={() => setRegion(r.id)}>
            {r.label}
          </button>
        ))}
      </div>
      <figure className="sl-fig">
        <svg viewBox={`0 0 ${W} ${H}`} width={W} height={H} aria-hidden="true" data-drawn={drawn || undefined} onPointerLeave={() => setHot(null)}>
          <text x={X0} y={12} className="sl-axis" textAnchor="middle">
            Q1
          </text>
          <text x={X1} y={12} className="sl-axis" textAnchor="middle">
            Q2
          </text>
          <line x1={X0} x2={X0} y1={TOP - 6} y2={BOTTOM + 6} className="sl-rule" />
          <line x1={X1} x2={X1} y1={TOP - 6} y2={BOTTOM + 6} className="sl-rule" />
          {shown.map((r, i) => {
            const on = r.channel === focus;
            const move = rb[i]! - ra[i]!;
            return (
              <g key={r.channel} className="sl-line" data-on={on || undefined} onPointerEnter={() => setHot(r.channel)}>
                <line x1={X0} y1={y(r.before)} x2={X1} y2={y(r.after)} className="sl-stroke" pathLength={1} />
                <line x1={X0} y1={y(r.before)} x2={X1} y2={y(r.after)} className="sl-hit" />
                <circle cx={X0} cy={y(r.before)} r={4} className="sl-dot" />
                <circle cx={X1} cy={y(r.after)} r={4} className="sl-dot" />
                <text x={X0 - 10} y={leftY[i]! + 4} textAnchor="end" className="sl-val">
                  {pct(target[i]!.before)}
                </text>
                <text x={X1 + 10} y={rightY[i]! + 4} className="sl-val">
                  <tspan className="sl-name">{r.channel}</tspan> {pct(target[i]!.after)}
                  {move !== 0 && <tspan className="sl-move">{` ${move > 0 ? "+" : "-"}${Math.abs(move)}`}</tspan>}
                </text>
              </g>
            );
          })}
        </svg>
        <figcaption className="sl-cap">Conversion rate by channel, Q1 to Q2. Figures beside each line move rank.</figcaption>
      </figure>
      <table className="sr-only">
        <caption>Conversion rate by channel, {REGIONS.find((r) => r.id === region)?.label}</caption>
        <thead>
          <tr>
            <th scope="col">Channel</th>
            <th scope="col">Q1</th>
            <th scope="col">Q2</th>
          </tr>
        </thead>
        <tbody>
          {target.map((r) => (
            <tr key={r.channel}>
              <th scope="row">{r.channel}</th>
              <td>{pct(r.before)}</td>
              <td>{pct(r.after)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// What a hovered card shows: Europe, then Asia Pacific, every line sliding to its new slope.
const TOUR: Tour = [
  { click: ".sl-region", text: "Europe", wait: 1200 },
  { click: ".sl-region", text: "Asia Pacific", wait: 1200 },
];

export default function SlopeChartEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Slope chart for before and after" tour={TOUR} sample>
      <SlopeDemo />
    </PieceStage>
  );
}

More like this

Donut that changes period

Hover, PressCharts and numbers

Context window meter

Hover, PressCharts and numbers

How the tools connect

HoverCharts and numbers

Balanced logo wall

Hover, PressPage sections

Traffic in stacked bars

HoverCharts and numbers

Sphere of dots that parts for the pointer

Hover, PressPage sections