Public
Edited
Oct 24, 2023
22 forks
19 stars
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

svg.append(defs);

const view = svg.append("rect")
.attr("class", "view")
.attr("x", 0.5)
.attr("y", 0.5)
.attr("width", width - 1)
.attr("height", height - 1);

const gX = svg.append("g").attr("class", "axis axis--x").call(xAxis);
const gY = svg.append("g").attr("class", "axis axis--y").call(yAxis);

const zoom = d3.zoom()
.scaleExtent([1, 40])
.translateExtent([[-100, -100], [width + 90, height + 100]])
.filter(filter)
.on("zoom", zoomed);

return Object.assign(svg.call(zoom).node(), {reset});

function zoomed({ transform }) {
view.attr("transform", transform);
gX.call(xAxis.scale(transform.rescaleX(x)));
gY.call(yAxis.scale(transform.rescaleY(y)));
}

function reset() {
svg.transition()
.duration(750)
.call(zoom.transform, d3.zoomIdentity);
}

// prevent scrolling then apply the default filter
function filter(event) {
event.preventDefault();
return (!event.ctrlKey || event.type === 'wheel') && !event.button;
}
}
Insert cell
defs = () => svg`<defs>
<style>
.axis .domain { display: none; }
.axis line { stroke-opacity: 0.3; shape-rendering: crispEdges; }
.view { fill: url(#gradient); stroke: #000; }
</style>

<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0.0%" stop-color="#2c7bb6"></stop>
<stop offset="12.5%" stop-color="#00a6ca"></stop>
<stop offset="25.0%" stop-color="#00ccbc"></stop>
<stop offset="37.5%" stop-color="#90eb9d"></stop>
<stop offset="50.0%" stop-color="#ffff8c"></stop>
<stop offset="62.5%" stop-color="#f9d057"></stop>
<stop offset="75.0%" stop-color="#f29e2e"></stop>
<stop offset="87.5%" stop-color="#e76818"></stop>
<stop offset="100.0%" stop-color="#d7191c"></stop>
</linearGradient>
`
Insert cell
x = d3.scaleLinear()
.domain([-1, width + 1])
.range([-1, width + 1])
Insert cell
y = d3.scaleLinear()
.domain([-1, height + 1])
.range([-1, height + 1])
Insert cell
xAxis = d3.axisBottom(x)
.ticks(((width + 2) / (height + 2)) * 10)
.tickSize(height)
.tickPadding(8 - height)
Insert cell
yAxis = d3.axisRight(y)
.ticks(10)
.tickSize(width)
.tickPadding(8 - width)
Insert cell
height = 500
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