Public
Edited
Jan 26
1 fork
Insert cell
Insert cell
Insert cell
<h1 id="chart-title"></h1>
Insert cell
<svg id="bar-chart"></svg>
Insert cell
<style>
#bar-chart {
border: solid 1px gray;
}
.category {
text-anchor: end;
}
text {
font-size: 10pt;
alignment-baseline: hanging;
}
</style>
Insert cell
Insert cell
jsonData = FileAttachment("sol_2019.json").json()
Insert cell
Insert cell
distances =
jsonData.planets
.map(obj => ({name: obj.name, distance: obj.semiMajorAxisAU}))
.sort((a,b) => d3.ascending(a.distance, b.distance));
Insert cell
dim = ({width: 600, height: 300})
Insert cell
barHeight = dim.height / distances.length - 2;
Insert cell
xscale = d3.scaleLinear().domain([0, d3.max(distances, d => d.distance)])
.range([0, dim.width-140]);
Insert cell
yscale = d3.scaleLinear().domain([0, distances.length])
.range([1, dim.height]);
Insert cell
color = d3.scaleOrdinal(d3.schemeTableau10)
.domain(yscale.domain());
Insert cell
fmt = d3.format(".2f")
Insert cell
d3.select("#chart-title")
.text("Average distance from the Sun");
Insert cell
svg = d3.select("#bar-chart")
.attr("width", dim.width)
.attr("height", dim.height)
Insert cell
entries = svg.selectAll(".entry")
.data(distances)
.join("g")
.attr("class", "entry")
.attr("transform", (d,i) => `translate(70, ${yscale(i)})`);
Insert cell
entries.append("rect")
.attr("class", "bar")
.attr("height", barHeight)
.attr("width", d => xscale(d.distance))
.style("fill", (d,i) => color(i));
Insert cell
entries.append("text")
.attr("class", "category")
.attr("x", -5)
.attr("y", (barHeight/2) - 5)
.text(d => d.name);
Insert cell
entries.append("text")
.attr("class", "value")
.attr("x", d => xscale(d.distance) + 5)
.attr("y", (barHeight/2) - 5)
.text(d => `${fmt(d.distance)} AU`);
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