Skip to content

Commit

Permalink
Merge branch 'main' into fil/monospace-width
Browse files Browse the repository at this point in the history
  • Loading branch information
Fil authored Oct 12, 2023
2 parents c3d047d + febdf62 commit 91c1a7c
Show file tree
Hide file tree
Showing 13 changed files with 187 additions and 27 deletions.
2 changes: 0 additions & 2 deletions docs/community.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ Please star ⭐️ our [GitHub repo](https://github.com/observablehq/plot) to sh

Plot is getting better all the time; catch up on [recent releases](https://github.com/observablehq/plot/releases) by reading our [CHANGELOG](https://github.com/observablehq/plot/blob/main/CHANGELOG.md).

For email updates, sign up for the [Observable Plot Twist](https://observablehq.com/@observablehq/plot-twist-newsletter-signup) newsletter. (See our [back issues](https://observablehq.com/collection/@observablehq/newsletters/2) and [blog](https://observablehq.com/blog), too.) This monthly newsletter will let you know about new features in Plot, inspiring work by the community, upcoming workshops and community events, and more.

And of course, follow us on [Observable](https://observablehq.com/@observablehq?tab=profile), [Mastodon](https://vis.social/@observablehq), [Twitter](https://twitter.com/observablehq), and [LinkedIn](https://www.linkedin.com/company/observable)!

## Getting help
Expand Down
2 changes: 1 addition & 1 deletion docs/marks/tip.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ Plot.plot({
```
:::

If you don’t specify an **anchor**, the tip mark will choose one automatically. It will prefer *top-left* if the tip fits; otherwise it will switch sides to try to contain the tip within the plot’s frame. When dynamically rendering the tip mark, say with the [pointer interaction](../interactions/pointer.md), the tip will also attempt to use the anchor it chose previously, making the tip more stable as you move the pointer and improving readability. In some cases, it may not be possible to fit the tip within the plot’s frame; consider setting the plot’s **style** to `overflow: visible;` to prevent the tip from being truncated.
If you don’t specify an explicit **anchor**, the tip mark will choose one automatically, using the **preferredAnchor** <VersionBadge pr="1872" /> if it fits. The preferred anchor defaults to *bottom*, except when using the **tip** option and the [pointerY pointing mode](../interactions/pointer.md), in which case it defaults to *left*. In some cases, it may not be possible to fit the tip within the plot’s frame; consider setting the plot’s **style** to `overflow: visible;` to prevent the tip from being truncated.

The tip mark is compatible with transforms that derive **x** and **y** dynamically from data, such as the [centroid transform](../transforms/centroid.md) which computes polygon centroids. Below, a map of the United States shows state names. We reduce the size of the tips by setting the **textPadding** option to 3 pixels instead of the default 8.

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"scripts": {
"test": "yarn test:mocha && yarn test:tsc && yarn test:lint && yarn test:prettier",
"test:coverage": "npx c8 yarn test:mocha",
"test:mocha": "mkdir -p test/output && mocha 'test/**/*-test.*' 'test/plot.js'",
"test:mocha": "mkdir -p test/output && TZ=America/Los_Angeles mocha 'test/**/*-test.*' 'test/plot.js'",
"test:lint": "eslint src test",
"test:prettier": "prettier --check src test",
"test:tsc": "tsc",
Expand Down
2 changes: 1 addition & 1 deletion src/marks/axis.js
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ export function inferTickFormat(scale, data, ticks, tickFormat, anchor) {
return typeof tickFormat === "function"
? tickFormat
: tickFormat === undefined && data && isTemporal(data)
? inferTimeFormat(data, anchor) ?? formatDefault
? inferTimeFormat(scale.type, data, anchor) ?? formatDefault
: scale.tickFormat
? scale.tickFormat(typeof ticks === "number" ? ticks : null, tickFormat)
: tickFormat === undefined
Expand Down
16 changes: 16 additions & 0 deletions src/marks/tip.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,28 @@ export interface TipOptions extends MarkOptions, TextStyles {
*/
anchor?: FrameAnchor;

/**
* If an explicit tip anchor is not specified, an anchor is chosen
* automatically such that the tip fits within the plot’s frame; if the
* preferred anchor fits, it is chosen.
*/
preferredAnchor?: FrameAnchor | null;

/**
* How channel values are formatted for display. If a format is a string, it
* is interpreted as a (UTC) time format for temporal channels, and otherwise
* a number format.
*/
format?: {[name in ChannelName]?: boolean | string | ((d: any, i: number) => string)};

/** The image filter for the tip’s box; defaults to a drop shadow. */
pathFilter?: string;

/** The size of the tip’s pointer in pixels; defaults to 12. */
pointerSize?: number;

/** The padding around the text in pixels; defaults to 8. */
textPadding?: number;
}

/**
Expand Down
27 changes: 19 additions & 8 deletions src/marks/tip.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export class Tip extends Mark {
y1,
y2,
anchor,
preferredAnchor = "bottom",
monospace,
fontFamily = monospace ? "ui-monospace, monospace" : undefined,
fontSize,
Expand Down Expand Up @@ -65,7 +66,7 @@ export class Tip extends Mark {
defaults
);
this.anchor = maybeAnchor(anchor, "anchor");
this.previousAnchor = this.anchor ?? "top-left";
this.preferredAnchor = maybeAnchor(preferredAnchor, "preferredAnchor");
this.frameAnchor = maybeFrameAnchor(frameAnchor);
this.textAnchor = impliedString(textAnchor, "middle");
this.textPadding = +textPadding;
Expand Down Expand Up @@ -208,16 +209,26 @@ export class Tip extends Mark {
(w = Math.round(w)), (h = Math.round(h)); // crisp edges
let a = anchor; // use the specified anchor, if any
if (a === undefined) {
a = mark.previousAnchor; // favor the previous anchor, if it fits
const x = px(i) + ox;
const y = py(i) + oy;
const fitLeft = x + w + r * 2 < width;
const fitRight = x - w - r * 2 > 0;
const fitTop = y + h + m + r * 2 + 7 < height;
const fitLeft = x + w + m + r * 2 < width;
const fitRight = x - w - m - r * 2 > 0;
const fitTop = y + h + m + r * 2 < height;
const fitBottom = y - h - m - r * 2 > 0;
const ax = (/-left$/.test(a) ? fitLeft || !fitRight : fitLeft && !fitRight) ? "left" : "right";
const ay = (/^top-/.test(a) ? fitTop || !fitBottom : fitTop && !fitBottom) ? "top" : "bottom";
a = mark.previousAnchor = `${ay}-${ax}`;
a =
fitLeft && fitRight
? fitTop && fitBottom
? mark.preferredAnchor
: fitBottom
? "bottom"
: "top"
: fitTop && fitBottom
? fitLeft
? "left"
: "right"
: (fitLeft || fitRight) && (fitTop || fitBottom)
? `${fitBottom ? "bottom" : "top"}-${fitLeft ? "left" : "right"}`
: mark.preferredAnchor;
}
const path = this.firstChild; // note: assumes exactly two children!
const text = this.lastChild; // note: assumes exactly two children!
Expand Down
3 changes: 2 additions & 1 deletion src/plot.js
Original file line number Diff line number Diff line change
Expand Up @@ -527,10 +527,11 @@ function inferTips(marks) {
if (tipOptions) {
if (tipOptions === true) tipOptions = {};
else if (typeof tipOptions === "string") tipOptions = {pointer: tipOptions};
let {pointer: p} = tipOptions;
let {pointer: p, preferredAnchor: a} = tipOptions;
p = /^x$/i.test(p) ? pointerX : /^y$/i.test(p) ? pointerY : pointer; // TODO validate?
tipOptions = p(derive(mark, tipOptions));
tipOptions.title = null; // prevent implicit title for primitive data
if (a === undefined) tipOptions.preferredAnchor = p === pointerY ? "left" : "bottom";
const t = tip(mark.data, tipOptions);
t.facet = mark.facet; // inherit facet settings
t.facetAnchor = mark.facetAnchor; // inherit facet settings
Expand Down
44 changes: 32 additions & 12 deletions src/time.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,23 +123,39 @@ for (const [name, interval] of utcIntervals) {
interval[intervalType] = "utc";
}

const utcFormatIntervals = [
["year", utcYear, "utc"],
["month", utcMonth, "utc"],
["day", unixDay, "utc", 6 * durationMonth],
["hour", utcHour, "utc", 3 * durationDay],
["minute", utcMinute, "utc", 6 * durationHour],
["second", utcSecond, "utc", 30 * durationMinute]
];

const timeFormatIntervals = [
["year", timeYear, "time"],
["month", timeMonth, "time"],
["day", timeDay, "time", 6 * durationMonth],
["hour", timeHour, "time", 3 * durationDay],
["minute", timeMinute, "time", 6 * durationHour],
["second", timeSecond, "time", 30 * durationMinute]
];

// An interleaved array of UTC and local time intervals, in descending order
// from largest to smallest, used to determine the most specific standard time
// format for a given array of dates. This is a subset of the tick intervals
// listed above; we only need the breakpoints where the format changes.
const formatIntervals = [
["year", utcYear, "utc"],
["year", timeYear, "time"],
["month", utcMonth, "utc"],
["month", timeMonth, "time"],
["day", unixDay, "utc", 6 * durationMonth],
["day", timeDay, "time", 6 * durationMonth],
utcFormatIntervals[0],
timeFormatIntervals[0],
utcFormatIntervals[1],
timeFormatIntervals[1],
utcFormatIntervals[2],
timeFormatIntervals[2],
// Below day, local time typically has an hourly offset from UTC and hence the
// two are aligned and indistinguishable; therefore, we only consider UTC, and
// we don’t consider these if the domain only has a single value.
["hour", utcHour, "utc", 3 * durationDay],
["minute", utcMinute, "utc", 6 * durationHour],
["second", utcSecond, "utc", 30 * durationMinute]
...utcFormatIntervals.slice(3)
];

function parseInterval(input, intervals, type) {
Expand Down Expand Up @@ -238,16 +254,20 @@ function getTimeTemplate(anchor) {
: (f1, f2) => `${f1}\n${f2}`;
}

function getFormatIntervals(type) {
return type === "time" ? timeFormatIntervals : type === "utc" ? utcFormatIntervals : formatIntervals;
}

// Given an array of dates, returns the largest compatible standard time
// interval. If no standard interval is compatible (other than milliseconds,
// which is universally compatible), returns undefined.
export function inferTimeFormat(dates, anchor) {
export function inferTimeFormat(type, dates, anchor) {
const step = max(pairs(dates, (a, b) => Math.abs(b - a))); // maybe undefined!
if (step < 1000) return formatTimeInterval("millisecond", "utc", anchor);
for (const [name, interval, type, maxStep] of formatIntervals) {
for (const [name, interval, intervalType, maxStep] of getFormatIntervals(type)) {
if (step > maxStep) break; // e.g., 52 weeks
if (name === "hour" && !step) break; // e.g., domain with a single date
if (dates.every((d) => interval.floor(d) >= d)) return formatTimeInterval(name, type, anchor);
if (dates.every((d) => interval.floor(d) >= d)) return formatTimeInterval(name, intervalType, anchor);
}
}

Expand Down
43 changes: 43 additions & 0 deletions test/output/timeAxisLocal.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
55 changes: 55 additions & 0 deletions test/output/tipLineX.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes
11 changes: 11 additions & 0 deletions test/plots/time-axis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,14 @@ export async function warnTimeAxisOrdinalExplicitIncompatibleTicks() {
marks: [Plot.barY(aapl, Plot.groupX({y: "median", title: "min"}, {title: "Date", x: "Date", y: "Close"}))]
});
}

export async function timeAxisLocal() {
const dates = [
"2023-09-30T15:05:48.452Z",
"2023-09-30T16:05:48.452Z",
"2023-09-30T17:05:48.452Z",
"2023-09-30T18:05:48.452Z",
"2023-09-30T19:05:48.452Z"
].map((d) => new Date(d));
return Plot.dotX(dates).plot({x: {type: "time"}});
}
7 changes: 6 additions & 1 deletion test/plots/tip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,12 @@ export async function tipHexbinExplicit() {
});
}

export async function tipLine() {
export async function tipLineX() {
const aapl = await d3.csv<any>("data/aapl.csv", d3.autoType);
return Plot.lineX(aapl, {y: "Date", x: "Close", tip: true}).plot();
}

export async function tipLineY() {
const aapl = await d3.csv<any>("data/aapl.csv", d3.autoType);
return Plot.lineY(aapl, {x: "Date", y: "Close", tip: true}).plot();
}
Expand Down

0 comments on commit 91c1a7c

Please sign in to comment.