Published
Edited
Sep 30, 2022
13 stars
Insert cell
Insert cell
Insert cell
plot = {
// select a point for which to provide details-on-demand
const hover = vl
.selectSingle()
.encodings("x") // limit selection to x-axis value
.on("mouseover") // select on mouseover events
.nearest(true) // select data point nearest the cursor
.empty("none"); // empty selection includes no data points

// define our base line chart of stock prices
const line = vl
.markLine()
.encode(
vl.x().fieldT("date"),
vl.y().fieldQ("price").scale({ type: "log" }),
vl.color().fieldN("symbol")
);

// shared base for new layers, filtered to hover selection
const base = line.transform(vl.filter(hover));

// mark properties for text label layers
const label = { align: "left", dx: 5, dy: -5 };
const white = { stroke: "white", strokeWidth: 2 };

return vl
.layer(
line,
// add a rule mark to serve as a guide line
vl
.markRule({ color: "#aaa" })
.transform(vl.filter(hover))
.encode(vl.x().fieldT("date")),
// add circle marks for selected time points, hide unselected points
line
.markCircle()
.select(hover) // use as anchor points for selection
.encode(vl.opacity().if(hover, vl.value(1)).value(0)),
// add white stroked text to provide a legible background for labels
base.markText(label, white).encode(vl.text().fieldQ("price")),
// add text labels for stock prices
base.markText(label).encode(vl.text().fieldQ("price"))
)
.width(300)
.height(100)
.facet(vl.fieldN("symbol"))
.columns(2)
.data("data/stocks.csv")
.render();
}
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more