import { select, scaleBand, scaleLinear, max, axisBottom,
axisLeft } from 'd3'; import data from './data.csv'; //
Convert CO2 values to numbers for (const d of data) { d.co2
= +d.co2; } export const main = (container) => { const width
= window.innerWidth; const height = window.innerHeight;
const margin = { top: 60, right: 40, bottom: 150, left: 80
}; const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom; //
Create SVG canvas const svg = select(container)
.selectAll('svg') .data([null]) .join('svg') .attr('width',
width) .attr('height', height); const g = svg.append('g')
.attr('transform',
`translate(${margin.left},${margin.top})`); // Scales const
xScale = scaleBand() .domain(data.map(d => d.country))
.range([0, innerWidth]) .padding(0.2); const yScale =
scaleLinear() .domain([0, max(data, d => d.co2)]) .nice()
.range([innerHeight, 0]); // Bars g.selectAll('rect')
.data(data) .join('rect') .attr('x', d => xScale(d.country))
.attr('y', d => yScale(d.co2)) .attr('width',
xScale.bandwidth()) .attr('height', d => innerHeight -
yScale(d.co2)) .attr('fill', 'steelblue'); // X Axis
g.append('g') .attr('transform',
`translate(0,${innerHeight})`)
.call(axisBottom(xScale).tickValues(xScale.domain().slice(0,
10))) // first 10 countries only .selectAll('text')
.attr('transform', 'rotate(-40)') .style('text-anchor',
'end'); // Y Axis g.append('g').call(axisLeft(yScale)); //
Axis Labels svg.append('text') .attr('x', width / 2)
.attr('y', height - 50) .attr('text-anchor', 'middle')
.style('font-size', '16px') .text('Country');
svg.append('text') .attr('x', -height / 2) .attr('y', 20)
.attr('transform', 'rotate(-90)') .attr('text-anchor',
'middle') .style('font-size', '16px') .text('CO₂ Emissions
(Mt)'); // Title svg.append('text') .attr('x', width / 2)
.attr('y', 30) .attr('text-anchor', 'middle')
.style('font-size', '20px') .style('font-weight', 'bold')
.text('Top CO₂ Emitting Countries'); };