Public
Edited
Dec 15, 2021
Insert cell
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
scalesAndAxes = {
const svg = d3.create("svg")
.attr('width', width)
.attr('height', 50);
const scale = d3.scaleBand().domain(['a','b','c']).range([0,500]);
const axis = d3.axisBottom().scale(scale);
// create a container to put the axis
const axis_container = svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(10,20)');
// call axis to create the SVG elements for you
//axis_container.call(axis);
axis(axis_container);

return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
chart = BarChart(data, {chartHeight: 350})
Insert cell
function BarChart(data, {
chartWidth = 800,
chartHeight = 600,
marginTop = 40,
marginBottom = 10,
marginLeft = 120,
marginRight = 20,
barHeight = 25
} = {}) {
const width = chartWidth - marginLeft - marginRight;
const height = chartHeight - marginTop - marginBottom;
// Creates sources <svg> element
const svg = d3.create("svg")
.attr('width', width + marginLeft + marginRight)
.attr('height', height + marginTop + marginBottom);

// Group used to enforce margin
const g = svg.append('g').attr('transform', `translate(${marginLeft},${marginTop})`);
// Render the chart with new data

// DATA JOIN use the key argument for ensurign that the same DOM element is bound to the same data-item
const rect = g.selectAll('rect').data(data, (d) => d.location.city).join(
// ENTER
// new elements
(enter) => {
const rect_enter = enter.append('rect').attr('x', 0);
rect_enter.append('title');
return rect_enter;
},
// UPDATE
// update existing elements
(update) => update,
// EXIT
// elements that aren't associated with data
(exit) => exit.remove()
);

// ENTER + UPDATE
// both old and new elements
rect
.attr('height', barHeight)
.attr('width', (d) => d.temperature * 7)
.attr('y', (d, i) => i * (barHeight + 5));

rect.select('title').text((d) => d.location.city);
return svg.node();
}
Insert cell
<style>
rect {
fill: steelblue;
fill-opacity: 0.8;
}
rect:hover {
fill-opacity: 1;
}
.axis {
font-size: smaller;
}
</style>
Insert cell
data = FileAttachment("weather.json").json()
Insert cell
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