{
const margin = {top: 50, right: 20, bottom: 70, left: 90};
const visWidth = width - margin.left - margin.right;
const visHeight = 500 - margin.top - margin.bottom;
const svg = d3.create('svg')
.attr('width', visWidth + margin.left + margin.right)
.attr('height', visHeight + margin.top + margin.bottom);
svg.append('text')
.attr("x", width / 2)
.attr("y", 0 + (margin.top))
.attr("text-anchor", "middle")
.text('Net Donations Given')
const g = svg.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
const recieved = d3.rollup(data, g => d3.sum(g.map(x => x.amount)), d => d.recipient)
const given = d3.rollup(data, g => d3.sum(g.map(x => x.amount)), d => d.donor)
const countries = new Set()
for (let [key, value] of recieved) {
countries.add(key)
}
for (let [key, value] of given) {
countries.add(key)
}
console.log(countries)
const net_ammounts = new Map()
for(let country of countries){
net_ammounts.set(country, (given.get(country) || 0 ) - (recieved.get(country) || 0))
}
let Q = Array.from(countries).sort((a, b) => net_ammounts.get(a) < net_ammounts.get(b))
console.log(Q)
const x = d3.scaleBand()
.domain(Q)
.range([0, visWidth]);
console.log('here')
console.log(d3.extent(net_ammounts.values()))
const y = d3.scaleLinear()
.domain(d3.extent(net_ammounts.values()))
.range([visHeight, 0]);
const y_abs_scale = d3.scaleLinear()
.domain([0, d3.max(net_ammounts.values()) - d3.min(net_ammounts.values())])
.range([0, visHeight]);
console.log(y_abs_scale(0))
console.log(y_abs_scale(10))
console.log(y_abs_scale(100000000000))
const xAxis = d3.axisBottom(x);
const yAxis = d3.axisLeft(y);
const points = g.selectAll('g')
.data(countries)
.join('g')
.attr('transform', d => `translate(${x(d)}, ${y(0)})`);
points.append('rect')
.attr('width', 10)
.attr('height', d => y_abs_scale(Math.abs(net_ammounts.get(d))))
.attr('fill', d => net_ammounts.get(d) > 0 ? 'steelblue' : 'red')
.attr('transform', d => `scale(${1}, ${net_ammounts.get(d) > 0 ? -1 : 1})`)
g.append('g')
.attr('transform', `translate(0,${visHeight + 10})`)
.call(xAxis).selectAll('text')
.attr("dx", -24)
.attr("dy", 12)
.attr("transform", "rotate(-45)")
g.append('g')
.call(yAxis)
.call(g => g.selectAll('.domain').remove())
return svg.node();
}