Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions docs/marks/waffle.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import * as Plot from "@observablehq/plot";
import * as d3 from "d3";
import {ref, shallowRef, onMounted} from "vue";
import statepop from "../data/us-state-population-2010-2019.ts";

const apples = ref(512);
const unit = ref(10);
Expand Down Expand Up @@ -47,7 +48,7 @@ Plot.waffleY(olympians, Plot.groupX({y: "count"}, {x: "sex"})).plot({x: {label:
Waffles are rendered using SVG patterns, making them more performant than alternatives such as the [dot mark](./dot.md) for rendering many points.
:::

The **unit** option determines the quantity each waffle cell represents; it defaults to one. The unit may be set to a value greater than one for large quantities, or less than one (but greater than zero) for small fractional quantities. Try changing the unit below to see its effect.
The **unit** option determines the quantity each waffle cell represents. The unit may be set to a value greater than one for large quantities, or less than one (but greater than zero) for small fractional quantities. Try changing the unit below to see its effect.

<p>
<span class="label-input">
Expand All @@ -72,6 +73,14 @@ Plot.waffleY(olympians, Plot.groupZ({y: "count"}, {fx: "date_of_birth", unit})).
Use [faceting](../features/facets.md) as an alternative to supplying an ordinal channel (_i.e._, *fx* instead of *x* for a vertical waffleY). The facet scale’s **interval** option then allows grouping by a quantitative or temporal variable, such as the athlete’s year of birth in the chart below.
:::

The **unit** defaults to *auto* <VersionBadge pr="2428" />: one, unless cells would then be smaller than 5 square pixels or larger than 50,000 square pixels. In that case, the unit is the power of 1,000 (such as 0.001, 1,000, or 1,000,000) that makes each cell between 10 and 10,000 square pixels. In the chart below of the ten most populous U.S. states in 2019, each cell represents a million people.

:::plot
```js
Plot.waffleX(statepop, {y: "State", x: "2019", sort: {y: "-x", limit: 10}}).plot({marginLeft: 100, x: {label: "Population (2019)", tickFormat: "s"}})
```
:::

While waffles typically represent integer quantities, say to count people or days, they can also encode fractional values with a partial first or last cell. Set the **round** option to true to disable partial cells, or to Math.ceil or Math.floor to round up or down.

Like bars, waffles can be [stacked](../transforms/stack.md), and implicitly apply the stack transform when only a single quantitative channel is supplied.
Expand Down Expand Up @@ -133,7 +142,7 @@ For required channels, see the [bar mark](./bar.md). The waffle mark supports th

The waffle mark supports a few additional options to control the rendering of cells:

* **unit** - the quantity each cell represents; defaults to 1
* **unit** - the quantity each cell represents; defaults to *auto* <VersionBadge pr="2428" />
* **multiple** - the number of cells per row (or column); defaults to undefined
* **gap** - the separation between adjacent cells, in pixels; defaults to 1
* **round** - whether to round values to avoid partial cells; defaults to false
Expand Down
9 changes: 7 additions & 2 deletions src/marks/waffle.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@ import type {BarXOptions, BarYOptions} from "./bar.js";
interface WaffleOptions {
/** The number of cells per row or column; defaults to undefined for automatic. */
multiple?: number;
/** The quantity each cell represents; defaults to 1. */
unit?: number;
/**
* The quantity each cell represents; defaults to *auto*: 1, unless cells
* would then be smaller than 5 or larger than 50,000 square pixels, in which
* case the power of 1,000 that makes each cell between 10 and 10,000 square
* pixels.
*/
unit?: number | "auto";
/** The gap in pixels between cells; defaults to 1. */
gap?: number;
/** If true, round to integers to avoid partial cells. */
Expand Down
30 changes: 23 additions & 7 deletions src/marks/waffle.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {extent, namespaces} from "d3";
import {valueObject} from "../channel.js";
import {create} from "../context.js";
import {composeRender} from "../mark.js";
import {hasXY, identity, indexOf, isObject} from "../options.js";
import {hasXY, identity, indexOf, isObject, keyword} from "../options.js";
import {applyChannelStyles, applyDirectStyles, applyIndirectStyles, getPatternId} from "../style.js";
import {template} from "../template.js";
import {initializer} from "../transforms/basic.js";
Expand All @@ -16,19 +16,19 @@ const waffleDefaults = {
};

export class WaffleX extends BarX {
constructor(data, {unit = 1, gap = 1, round, multiple, ...options} = {}) {
constructor(data, {unit, gap = 1, round, multiple, ...options} = {}) {
super(data, wafflePolygon("x", options), waffleDefaults);
this.unit = Math.max(0, unit);
this.unit = maybeUnit(unit);
this.gap = +gap;
this.round = maybeRound(round);
this.multiple = maybeMultiple(multiple);
}
}

export class WaffleY extends BarY {
constructor(data, {unit = 1, gap = 1, round, multiple, ...options} = {}) {
constructor(data, {unit, gap = 1, round, multiple, ...options} = {}) {
super(data, wafflePolygon("y", options), waffleDefaults);
this.unit = Math.max(0, unit);
this.unit = maybeUnit(unit);
this.gap = +gap;
this.round = maybeRound(round);
this.multiple = maybeMultiple(multiple);
Expand All @@ -40,7 +40,7 @@ function wafflePolygon(y, options) {
const y1 = `${y}1`;
const y2 = `${y}2`;
return initializer(waffleRender(options), function (data, facets, channels, scales, dimensions) {
const {round, unit} = this;
const {round} = this;
const Y1 = channels[y1].value;
const Y2 = channels[y2].value;

Expand All @@ -49,8 +49,18 @@ function wafflePolygon(y, options) {
const barwidth = this[y === "y" ? "_width" : "_height"](scales, xy, dimensions);
const barx = this[y === "y" ? "_x" : "_y"](scales, xy, dimensions);

// Auto unit: if the scale of a unit makes it so small that it is invisible,
// or conversely insanely large, adopt a different power of 10^3.
const p = scaleof(scales.scales[y]); // pixel length per unit of 1
let {unit} = this;
if (unit === "auto") {
const area = barwidth * p; // pixel area per unit of 1
if (area < 5 || area > 5e4) unit = 1000 ** Math.ceil((1 - Math.log10(area)) / 3);
else unit = 1;
}

// The length of a unit along y in pixels.
const scale = unit * scaleof(scales.scales[y]);
const scale = unit * p;

// The number of cells on each row (or column) of the waffle.
const {multiple = Math.max(1, Math.floor(Math.sqrt(barwidth / scale)))} = this;
Expand Down Expand Up @@ -301,3 +311,9 @@ function waffleTip(tip) {
? {...tip, maxRadius: Infinity}
: undefined;
}

function maybeUnit(unit = "auto") {
if (typeof unit === "string" && isNaN(unit)) return keyword(unit, "unit", ["auto"]);
if (!((unit = +unit) > 0) || !isFinite(unit)) throw new Error(`invalid unit: ${unit}`);
return unit;
}
15 changes: 15 additions & 0 deletions test/marks/waffle-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as Plot from "@observablehq/plot";
import {assert, it} from "vitest";

it("waffle accepts a numeric or auto unit", () => {
assert.strictEqual(Plot.waffleY([1]).unit, "auto");
assert.strictEqual(Plot.waffleY([1], {unit: 10}).unit, 10);
assert.strictEqual(Plot.waffleY([1], {unit: "10"}).unit, 10);
assert.strictEqual(Plot.waffleX([1], {unit: "Auto"}).unit, "auto");
});

it("waffle rejects an invalid unit", () => {
for (const unit of [0, -1, Infinity, NaN, "foo"]) {
assert.throws(() => Plot.waffleY([1], {unit}), /invalid unit/);
}
});
79 changes: 79 additions & 0 deletions test/output/waffleAutoUnit.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions test/plots/waffle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,3 +431,10 @@ test(function waffleShapes() {
]
});
});

test(function waffleAutoUnit() {
return Plot.plot({
marginLeft: 60,
marks: [Plot.waffleY([1e6, 2e6, 3e6], {x: ["a", "b", "c"], fill: ["a", "b", "c"]}), Plot.ruleY([0])]
});
});
Loading