Public
Edited
Apr 21, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
svg = d3.select('body').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', +
'translate(' + margin.left + ',' + margin.top + ')'); //move the group element to the top left margin

Insert cell
Insert cell
//read in the data from our file
d3.json('data.json').then(function (data) {
//Optional: format the data elements
data.forEach(function(d) {
d.name = d.id; //TODO:update with name of field you want on the X axis
d.value = +d.value; //TODO:update with name of field you want on Y axis
});
//scale the range of the data in the domains for the axis
x.domain(data.map(function(d) { return d.name; })); //TODO: update with name of field for X axis
y.domain([0, d3.max(data, function(d) { return d.value; })]);

var xAxis = d3.axisBottom(x);
var yAxis = d3.axisLeft(y);
//append the x axis to the svg
xAxis = svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height+ ')')
.call(xAxis) //calls the axis and lets it know its position
.append('text')
.style('text-anchor', 'middle')
.attr('x', width + 20) //change numbers to adjust position
.attr('y', -6)
.style("fill", "black")
.text('Update Me');
//append the x axis to the svg
yAxis = svg.append('g')
.attr('class', 'y axis')
.attr("transform", "translate(20,0)")
.call(yAxis) //calls the axis
.append('text')
.attr('transform', 'rotate(-90)')
.attr('y', 6)
.attr('dy', '.71em')
.style('text-anchor', 'end')
.style("fill", "black")
.text('Update Me');
//append the rectangles for the bar chart
svg.selectAll('bar')
.data(data)
.enter().append('rect')
.style('fill', 'steelblue')
.attr('x', function(d) {
return x(d.name); //set the its position on the X axis
})
.attr('width', x.bandwidth()) //set width of the rectangle; change to width if not using categorical variable
.attr('y', function(d) {
return y(d.value); //set the position on the Y axis
})
.attr('height', function(d) {
return height - y(d.value); //calculate height of the bar
});
});
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