Published
Edited
Jun 1, 2022
Fork of Simple D3
Insert cell
Insert cell
{

const width = 900
const height = 600
const padding = 25
const svg = d3.create('svg')
.attr('width', width)
.attr('height', height)

svg.append("rect")
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "#121212");

async function fetchPlanets() {
let planets = []
for(let i = 1; i <= 6; i++) {
const response = await fetch(`https://swapi.dev/api/planets/?page=${i}`)
const data = await response.json()
data.results.forEach(obj => {
obj.gravity = +obj.gravity.split(" ", 1)[0]
obj.population = +obj.population
})

const filteredData = data.results.filter(d => d.diameter !== 'unknown')
planets.push(...filteredData)
}
return planets
}

const planets = await fetchPlanets()

const climates = ['temperate', 'tropical', 'frozen', 'frigid', 'arid', 'murky', 'polluted', 'hot', 'superheated']

const xScale = d3.scaleLog()
.domain([d3.min(planets, d => d.population) + 1, d3.max(planets, d => d.population) + 1])
.range([padding, width - padding])

const yScale = d3.scaleLinear()
.domain([d3.min(planets, d => d.gravity), d3.max(planets, d => d.gravity)])
.range([padding, height - padding])

//axes
const xAxis = d3.axisBottom(xScale)

const yAxis = d3.axisLeft(yScale).ticks(5)

const color = d3.scaleOrdinal()
.domain(climates)
.range(['#90BE6D', '#43AA8B', '#277DA1', '#4D908E', '#F9C74F', '#F5F5F5', '#577590', '#F3722C', '#F94144'])

const size = d3.scaleLinear()
.domain([0, d3.max(planets, d => d.diameter)])
.range([0, 10])

var circles = svg.selectAll()
.data(planets)
.enter()
.append('circle')
.attr('r', d => size(d.diameter / 2))
.attr('cx', d => d.population ? xScale(d.population) : padding)
.attr('cy', d => d.gravity ? yScale(d.gravity): padding)
.attr('fill', d => climates.includes(d.climate) ? color(d.climate) : 'lightgrey')
/*
var text = svg.selectAll()
.data(planets)
.enter()
.append('text')
.attr('x', d => d.population? xScale(d.population) : padding)
.attr('y', d => d.gravity ? yScale(d.gravity) : padding)
.attr('font-family', 'Proxima')
.attr('font-size', '10px')
.text(d => d.name)
*/

svg.append("g")
.call(xAxis)
.attr('transform', 'translate(0,' + height / 2+ ')')
.attr('stroke-width', .5)
.attr('stroke-dasharray', '3 3')
.attr('color', '#F5F5F5')

svg.append("g")
.call(yAxis)
.attr('transform', 'translate(' + width /2 + ',0)')
.attr('stroke-width', 0)
.attr('color', '#F5F5F5')

return svg.node()
}
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more