Published
Edited
Apr 7, 2022
Insert cell
Insert cell
{
// And there we go!! Thanks for watching!!
// First lets load the data. I have some penguin data from ObservableHq. Lets explore it!!
const data = await FileAttachment('penguins.csv').csv({typed: true});

// We're going to chart two properties flipper_length_mm and body_mass_g
// First lets access them
const yAccessor = d => d.body_mass_g;
const xAccessor = d => d.flipper_length_mm;

// Awesome now lets define the dimensions of our chart. We are going to add a wrapper to give us a little space between the sides and the drawing space
const dimensions = {
width: width,
height: 400,
margin: {
top: 20,
right: 20,
bottom: 20,
left: 20,
}
};
dimensions.innerWidth = dimensions.width
- dimensions.margin.left
- dimensions.margin.right;
dimensions.innerHeight = dimensions.height
- dimensions.margin.top
- dimensions.margin.bottom;

// Okay now lets define our scales. Scales essentially turn a data point into a position on the chart
const xScale = d3.scaleLinear()
.domain(d3.extent(data, xAccessor)).nice()
.range([0, dimensions.innerWidth]);
const yScale = d3.scaleLinear()
.domain(d3.extent(data, yAccessor)).nice()
.range([dimensions.innerHeight, 0]); // This is backwards because your y point goes from top to bottom

// Finally lets draw something. First define the canvas
const wrapper = d3.create('svg')
.attr('viewBox', [0, 0, dimensions.width, dimensions.height]);
const chart = wrapper.append('g')
.style('transform', `translate(${dimensions.margin.left}px, ${dimensions.margin.top}px)`); // Here we are moving the inner chart a little to the right and down. I'll show you in the browser tools
// Make sure to add px. See how the group was shifted slightly right and down?

// Okay lets draw our circles
chart.append('g')
.selectAll('circle')
.data(data)
.join('circle')
.filter(d => d.body_mass_g)
.attr('cx', d => xScale(xAccessor(d)))
.attr('cy', d => yScale(yAccessor(d))) // Make sure to add the d
.attr('r', 5)
.attr('fill', 'lightblue');

// Okay now lets draw our x axis and y axis
// First lets create a generator for each
const xAxisGenerator = d3.axisBottom().scale(xScale);
const yAxisGenerator = d3.axisLeft().scale(yScale);
// Now lets draw the axis
const xAxis = chart.append('g').call(xAxisGenerator) // Hmm we need to move the x axis to the bottom so lets translate
.style('transform', `translateY(${dimensions.innerHeight}px)`)
const yAxis = chart.append('g').call(yAxisGenerator);
return wrapper.node();
}
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