Public
Edited
Feb 23, 2024
9 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3.forceSimulation( data )
.force('x', d3.forceX().strength(0.2).x(d => xScale(d.dem/d.total)) )
.force('y', d3.forceY().strength(0.05).y(margin.top + height / 2) )
.force('collide', d3.forceCollide().radius(d => d.r + 1 ).strength(1) )
Insert cell
Insert cell
chart = {
const svg = d3.create('svg')
.attr('width', width)
.attr('height', height)

data.forEach(d => d.r = rScale(d.electoralVotes))

const simulation = d3.forceSimulation( data )
.force('x', d3.forceX().strength(0.2).x(d => xScale(d.dem/d.total)) )
.force('y', d3.forceY().strength(0.05).y(margin.top + height / 2) )
.force('collide', d3.forceCollide().radius(d => d.r + 1 ).strength(1) )


const g = svg.selectAll('g.node')
.data( simulation.nodes() )
.join('g')
.attr('class', 'node')
.call( g => g
.append('circle')
.attr('r', d => d.r)
.style('fill', d => color(Math.round(d.dem/d.total)))
.style('opacity', 0.9)
)
.call( g => g
.append('title')
.text(d => `${d.state}\nDem: ${d.dem.toLocaleString()}\nRep: ${d.rep.toLocaleString()}\nTotal: ${ d.total.toLocaleString() }\nElectoral votes: ${d.electoralVotes}\n`)
)
svg.append('g')
.attr('class', 'x-axis')
.attr('transform', `translate(0,${ height/2 })`)
.call(xAxis)
// On each iteration (tick) of the simulation, we update the position of our groups
simulation.on("tick", () => g.attr('transform', d => `translate(${ d.x },${ d.y })`) )
return svg.node()
}
Insert cell
Insert cell
Insert cell
color = d3.scaleLinear(
[ 0, 1 ],
[ '#e91d0e', '#3E36F8' ]
)
Insert cell
rScale = d3.scaleSqrt()
.domain([ 0, d3.max(data, d => d.electoralVotes)])
.range([ 0, maxRadius ])
Insert cell
xScale = d3.scaleLinear()
.range([ margin.left, width - margin.right ])
Insert cell
xAxis = d3.axisBottom( xScale )
.tickValues([0,0.5,1])
.tickFormat(
d3.scaleOrdinal(
[0,0.5,1],
['100% Repulican','Split','100% Democrat']
)
)
Insert cell
margin = ({
top: 10,
right: 50,
bottom: 10,
left: 50
})
Insert cell
Insert cell
Insert cell
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