Published
Edited
Mar 29, 2020
Importers
Insert cell
md`# My chart`
Insert cell
plotOptions = ({
title: 'Incremento % giornaliero',
xField: 'date',
xScale: 'linear',
xLabel: 'Data',
xLabelTransform: 'timeFormat(datum.date, "%d/%m")',
// xFormat: '',
yField: 'incrementPercent',
yScale: 'linear',
yLabel: 'Incremento %',
yLabelTransform: '(round(datum.incrementPercent * 10000) / 100) + "%"',
yFormat: '%',
});
Insert cell
function chart(inputData, plotOptions) {
// 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

const line = vl.markLine({point: true})
.encode(
vl.x()
.fieldT(plotOptions.xField)
.axis({ title: plotOptions.xLabel, format: plotOptions.xFormat })
.scale({type: plotOptions.xScale}),
vl.y()
.fieldQ(plotOptions.yField)
.axis({ title: plotOptions.yLabel, format: plotOptions.yFormat })
.scale({type: plotOptions.yScale}),
)
.title(plotOptions.title)
.width(400);

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

// mark properties for text label layers
const ylabel = {align: 'left', dx: -25, dy: -15};
const xLabel = {align: 'left', dx: -25, dy: -30};
const white = {stroke: 'white', strokeWidth: 10};

return vl.data(inputData)
.transform([
vl.calculate(plotOptions.xLabelTransform).as('xLabel'),
vl.calculate(plotOptions.yLabelTransform).as('yLabel'),
])
.layer(
line,
// add a rule mark to serve as a guide line
vl.markRule({color: '#aaa'})
.transform(vl.filter(hover))
.encode(vl.x().fieldT(plotOptions.xField)),
// 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(ylabel, white).encode(vl.text().field('yLabel')),
// add text labels for stock prices
base.markText(ylabel).encode(vl.text().field('yLabel')),
// add white stroked text to provide a legible background for labels
base.markText(xLabel, white).encode(vl.text().field('xLabel')),
// add text labels for stock prices
base.markText(xLabel).encode(vl.text().field('xLabel'))
);
};
Insert cell
import { vl } from '@vega/vega-lite-api'
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