Published
Edited
Nov 27, 2021
1 fork
1 star
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

svg.append("g")
.call(xAxis);

svg.append("g")
.call(yAxis);

svg.append("g")
.call(grid);

svg.append("g")
.attr("stroke", "none")
.attr("fill", "black")
.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => x(new Date(d.publicationYear)))
.attr("cy", d => y(d.avgRating))
.attr("r", 4);

svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("text")
.data(data);

return svg.node();
}
Insert cell
x = d3.scaleTime()
.domain(
[new Date("1740-01-01 00:00:00"), new Date("2020-12-31 00:00:00")])
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain(d3.extent(data, d => d.avgRating)).nice()
.range([height - margin.bottom, margin.top]);
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(width / 80))
.call(g => g.select(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove())
Insert cell
grid = g => g
.attr("stroke", "#eee")
.attr("stroke-dasharray",3)
.call(g => g.append("g")
.selectAll("line")
.data(x.ticks())
.join("line")
.attr("x1", d => 0.5 + x(d))
.attr("x2", d => 0.5 + x(d))
.attr("y1", margin.top)
.attr("y2", height - margin.bottom))
.call(g => g.append("g")
.selectAll("line")
.data(y.ticks())
.join("line")
.attr("y1", d => 0.5 + y(d))
.attr("y2", d => 0.5 + y(d))
.attr("x1", margin.left)
.attr("x2", width - margin.right));
Insert cell
tooltip = {
chart // Observable work around to make sure charts on page before creating tooltip
const tooltip = d3.select("body").append("div")
.attr("class", "svg-tooltip")
.style("position", "absolute")
.style("visibility", "hidden");

d3.selectAll("circle")
.on("mouseover", function(event, d){
tooltip.style("visibility", "visible").text(d.title);
})
.on("mousemove", function(event){
tooltip.style("top", (event.pageY-10)+"px").style("left",(event.pageX+10)+"px");
})
.on("mouseout", function(){
tooltip.style("visibility", "hidden");
});
return tooltip;
}
Insert cell
Insert cell
height = 600;
Insert cell
margin = ({top: 25, right: 20, bottom: 35, left: 40})
Insert cell
data = FileAttachment("data200.json").json();
Insert cell
d3 = require("d3@7")
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