Published
Edited
Feb 2, 2021
2 forks
43 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require('d3@v6')
Insert cell
Insert cell
data = [8, 18, 7, 10, 19, 20, 10, 10, 6, 19, 17, 18, 23, 23, 13, 12, 15, 6, 9, 8];
Insert cell
Insert cell
chartWidth = 400
Insert cell
chartHeight = 200
Insert cell
Insert cell
xScale = d3.scaleLinear()
.domain([0, data.length])
.range([0, chartWidth])
Insert cell
yScale = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([0, chartHeight]);
Insert cell
Insert cell
Insert cell
{
const svg = d3.create("svg")
.attr('width',chartWidth)
.attr('height',chartHeight)

svg.append("g")
.attr("fill", 'aqua')
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", (d, i) => xScale(i))
.attr("y", d => -yScale(d)+chartHeight)
.attr("height", d => yScale(d))
.attr("width", 10);


return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function drawChart(container, data) {
const chartWidth = 400;
const chartHeight = 400;

const xScale = d3
.scaleLinear()
.domain([0, data.length])
.range([0, chartWidth]);

const yScale = d3
.scaleLinear()
.domain([0, d3.max(data)])
.range([0, chartHeight]);

// This is the first and only difference: instead of creating SVG, we are appending it to container
const svg = d3
.select(container)
.append('svg')
.attr('width', chartWidth)
.attr('height', chartHeight);

svg
.append("g")
.attr("fill", 'aqua')
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", (d, i) => xScale(i))
.attr("y", d => -yScale(d) + chartHeight)
.attr("height", d => yScale(d))
.attr("width", 10);
}
Insert cell
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