Public
Edited
Jan 2, 2024
Insert cell
Insert cell
Insert cell
data2@2.csv
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
{
const width = 900;
const height = 500;
const marginTop = 25;
const marginRight = 50;
const marginBottom = 70;
const marginLeft = 40;

//create the <svg>
const svg = d3
.create("svg")
.attr("width", width + marginLeft + marginRight)
.attr("height", height + marginTop + marginBottom);

//create the <g> to contain the chart
const g = svg
.append("g")
.attr("transform", `translate(${marginLeft}, ${marginTop})`);

// sort data in descending order
var sorted_data = data22.sort(function(b, a) {
return a.VALUE - b.VALUE;
});

//slice data for top values
sorted_data = sorted_data.filter(function(d,i){
return i < 10;
});
// X scale
var x = d3.scaleBand()
.domain(sorted_data.map(function(d) { return d.NAME; }))
.range([ 0, width ])
.padding(0.5);

// Y scale
var y = d3.scaleLinear()
.domain(d3.extent(sorted_data, (d, i)=> d.VALUE))
.range([ height, 0]);

//add x axis
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.selectAll("text")
.attr("transform", "translate(-10,0)rotate(-45)")
.style("text-anchor", "end");

//add y axis
g.append("g")
.call(d3.axisLeft(y));

// Add X axis label:
g.append("text")
.attr("text-anchor", "end")
.attr("x", width)
.attr("y", height + marginTop)
.text("Country");

// Add Y axis label:
g.append("text")
.attr("text-anchor", "end")
.attr("transform", "rotate(-90)")
.attr("x", 0)
.attr("y", 0)
.text("Billions ($)");

// generate bar chart
g.selectAll("mybar")
.data(sorted_data)
//.enter()
.join("rect") // for each data point, create a rect
.attr("x", function(d) { return x(d.NAME); }) //x value is the name
.attr("y", function(d) { return y(d.VALUE); }) //y value is the value
.attr("width", x.bandwidth()) // bar width is automatically set
.attr("height", function(d) { return height - y(d.VALUE); }) // calculate bar width
.attr("fill", "#69b3a2") // bar is color green

//generate svg
return svg.node();

}

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