Skip to main content
100%

Making a Bar Chart

✓ Published0🌍 Public
AAniketh-Samson
Last edited Mar 5, 2020
Created on Mar 4, 2020
Forked from Making a Bar Chart

This bar chart displays the population of the ten most populous countries, using 2018 estimates from the United Nations World Population Prospects. The chart uses D3 v4 with an SVG rendering approach, employing `scaleLinear` for the population axis and `scaleBand` for the country categories. The visualization demonstrates custom axis formatting with `axisBottom` and `axisLeft`, including tick label conversion from billions to a readable format. Data is loaded from a CSV file using `csv`, and the chart includes styled axes, a title, and an x-axis label through D3's selection and append methods.

AI-generated description

This bar chart shows population of the top 10 most populous countries. The data comes from the year 2018 estimate in United Nations: World Population Prospects 2017. It also demonstrates customization of D3 axes.

const titleText = 'Top 10 Most Populous Countries'; const xAxisLabelText = 'Population';

const svg = select('svg');

const width = +svg.attr('width'); const height = +svg.attr('height');

const render = data => { const xValue = d => d['population']; const yValue = d => d.country; const margin = { top: 50, right: 40, bottom: 77, left: 180 }; const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom;

const xScale = scaleLinear() .domain([0, max(data, xValue)]) .range([0, innerWidth]);

const yScale = scaleBand() .domain(data.map(yValue)) .range([0, innerHeight]) .padding(0.1);

const g = svg.append('g') .attr('transform', translate(${margin.left},${margin.top}));

const xAxisTickFormat = number => format('.3s')(number) .replace('G', 'B');

const xAxis = axisBottom(xScale) .tickFormat(xAxisTickFormat) .tickSize(-innerHeight);

g.append('g') .call(axisLeft(yScale)) .selectAll('.domain, .tick line') .remove();

const xAxisG = g.append('g').call(xAxis) .attr('transform', translate(0,${innerHeight}));

xAxisG.select('.domain').remove();

xAxisG.append('text') .attr('class', 'axis-label') .attr('y', 65) .attr('x', innerWidth / 2) .attr('fill', 'black') .text(xAxisLabelText);

g.selectAll('rect').data(data) .enter().append('rect') .attr('y', d => yScale(yValue(d))) .attr('width', d => xScale(xValue(d))) .attr('height', yScale.bandwidth());

g.append('text') .attr('class', 'title') .attr('y', -10) .text(titleText); };

<!DOCTYPE html> <html lang="en"> <head> <script src="https://d3js.org/d3.v4.min.js"></script> </head> <body> <script> // write your d3 code here.. </script> </body> </html>
MIT Licensed

Similar vizzes