<!DOCTYPEhtml><html><head><title>Axes</title><scriptsrc="https://d3js.org/d3.v5.min.js"></script></head><body><svgwidth="960"height="500"id="mainsvg"class="svgs"></svg><script>const data =[{country:"China",population:"1415046"},{country:"India",population:"1354052"},{country:"United States",population:"326767"},{country:"Indonesia",population:"266795"},{country:"Brazil",population:"210868"},{country:"Pakistan",population:"200814"},{country:"Nigeria",population:"195875"},{country:"Bangladesh",population:"166368"},{country:"Russia",population:"143965"},{country:"Mexico",population:"130759"}]const svg = d3.select('#mainsvg');const width =+svg.attr('width');const height =+svg.attr('height');const margin ={top:60,right:30,bottom:60,left:150};const innerWidth = width - margin.left - margin.right;const innerHeight = height - margin.top - margin.bottom;constxValue=(datum)=>{return datum.population
};constyValue=(datum)=>{return datum.country
};constrender=function(data){// Linear Scale: Data Space -> Screen Space; const xScale = d3.scaleLinear().domain([0, d3.max(data, xValue)]).range([0, innerWidth]);// Introducing y-Scale; const yScale = d3.scaleBand().domain(data.map(yValue)).range([0, innerHeight]).padding(0.1);// The reason of using group is that nothing is rendered outside svg, so margin of svg is always blank while margin of group is rendered inside svg; const g = svg.append('g').attr('transform',`translate(${margin.left}, ${margin.top})`);// Do the data join (Enter)
g.selectAll('rect').data(data).enter().append('rect').attr('y',datum=>yScale(yValue(datum))).attr('width',(datum)=>{returnxScale(xValue(datum))})// use xSacle to re-scale data space (domain) and return the rescaled population; .attr('height', yScale.bandwidth()).attr('fill','steelblue')// Adding axes; const yAxis = d3.axisLeft(yScale);const xAxis = d3.axisBottom(xScale).tickFormat(d3.format('.3s')).tickSize(-innerHeight);let yAxisGroup = g.append('g').call(yAxis);
yAxisGroup.selectAll('.domain, .tick line').remove();// we can select multiple tags using comma to seperate them and we can use space to signify nesting; let xAxisGroup = g.append('g').call(xAxis).attr('transform',`translate(${0}, ${innerHeight})`);
xAxisGroup.append('text').attr('y',50).attr('x', innerWidth /2).attr('fill','black').text('Population').attr('id','population');
xAxisGroup.selectAll('.domain').remove();// Adding a title;
g.append('text').text('Top 10 Most Populous Countries').attr('y',-10).attr('x',80);}render(data);// d3.csv('./static/data/population.csv')// .then(function(data) {// data.forEach(datum => {// //datum.population = parseFloat(datum.population);// datum.population = +(datum.population);// })// console.log(data);// console.log(data.map((datum) => {// return datum.country;// }))// render(data);// });</script></body></html>