Published
Edited
Apr 4, 2018
Insert cell
Insert cell
Insert cell
Insert cell
{
function dragged(d) {
// d3.event exposes dx and dy, which tell us how far the target has been
// dragged since the last "drag" event, so we just update the x and y
// properties on that datum and update the SVG.
d.x += d3.event.dx;
d.y += d3.event.dy;
update();
}
function update() {
svg.selectAll("rect")
.attr("x", d => d.x)
.attr("y", d => d.y);
svg.selectAll("path").attr("d", link);
}
// DOM.svg is just an Observable utility for creating an SVG node
const svg = d3.select(DOM.svg(width, height));
// Create some data for the nodes
const data = [
{
x: width / 10,
y: 60,
height: 80,
width: 100
},
{
x: 3 * width / 4,
y: height / 2,
height: 140,
width: 100
}
];
// Define connections between nodes
const links = [
{
source: data[0],
target: data[1]
}
];
// Set up the utility for generating path strings
const link = d3.linkHorizontal()
.source(function (d) {
// Calculate the (x, y) position for the link attachment
// on the source node.
return [
d.source.x + d.source.width,
d.source.y + (d.source.height / 2)
]
})
.target(function (d) {
return [
d.target.x,
d.target.y + (d.target.height / 2)
];
});
// Set up D3's drag behavior
const drag = d3.drag().on("drag", dragged);
// Initialize the nodes
svg.selectAll("rect").data(data)
.enter().append("rect")
.attr("x", d => d.x)
.attr("y", d => d.y)
.attr("width", d => d.width)
.attr("height", d => d.height)
.style("fill", "white")
.style("stroke", "#56445D")
.style("stroke-width", "2px")
.call(drag); // Apply the drag behvaior to all rects
// Initilize the links between nodes
svg.selectAll("path").data(links)
.enter().append("path")
.attr("d", link)
.style("fill", "none")
.style("stroke", "#56445D")
.style("stroke-width", "4px");
// This is just to tell the notebook to show the SVG.
return svg.node();
}
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