Published
Edited
Apr 26, 2020
Fork of Arc diagram
1 fork
Insert cell
Insert cell
Insert cell
/*code references:
1. https://observablehq.com/@d3/arc-diagram (for the general structure of code)
2. https://www.d3-graph-gallery.com/graph/interactivity_tooltip.html (d3 tooltip gallery)
3. https://observablehq.com/d/352a528406ce91dc (lab12, for building dropdown menu)
4. https://observablehq.com/@dorrietang/candy-diagram-mapping-candies-to-features (got inspirations to add text to dynamically visualize the number of connection each characters shares) */


chart2 = {
let div = d3.create('div');
let selector = div.append('select');
const displayChoices = ["Choose to display","Show all links", "Only same group", "Only different group"]
const items = selector
.selectAll('options')
.data(displayChoices)
.enter()
.append('option')
.text(function (d) { return d; })
.attr("value", function (d) { return d; })
items.filter(function(d) {return d.value === "Choose to display"})
.attr("selected",true);
const svg = div
.append('svg')
.attr('width', 1000)
.attr('height', 1200);
svg.append("style").text(`

.hover path {
stroke: #ccc;
}

.hover g.primary text {
fill: black;
font-weight: bold;
}

.hover g.secondary text {
fill: #333;
}

.hover g.secondary circle {
r: 5;
}

.hover g.primary circle {
r: 10;
}

.hover path.primary {
stroke: black;
stroke-opacity: 1;
}

`);

const label = svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("text-anchor", "end")
.selectAll("g")
.data(graph.nodes)
.join("g")
.attr("transform", d => `translate(${margin.left},${d.y = y(d.id)})`)
.call(g => g.append("text")
.attr("x", -6)
.attr("dy", "0.35em")
//.attr("fill", d => d3.lab(color(d.group)).darker(2))
.text(d => d.id))
.attr("fill", "white")
.call(g => g.append("circle")
.attr("r", 3)
.attr("id", d=>d.id)
.attr("fill", d => color(d.group))
/* .on("mouseover", function(d){
g.attr("r",d=> d.sourceLinks.length+d.targetLinks.length)}
)*/
)
label.on("mouseover",function(d){
label.selectAll('circle').attr('r',10)});
var tooltip = d3.selectAll("g")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("a simple tooltip");
function addTooltip(circle) {
var x = parseFloat(circle.attr("cx"));
var y = parseFloat(circle.attr("cy"));
var r = parseFloat(circle.attr("r"));
var text = circle.attr("id");

var tooltip = d3.select("g")
.append("text")
.text(text)
.attr("x", x)
.attr("y", y)
.attr("dy", -r * 2)
.attr("id", "tooltip");

var offset = tooltip.node().getBBox().width / 2;

if ((x - offset) < 0) {
tooltip.attr("text-anchor", "start");
tooltip.attr("dx", -r);
}
else if ((x + offset) > (width - margin)) {
tooltip.attr("text-anchor", "end");
tooltip.attr("dx", r);
}
else {
tooltip.attr("text-anchor", "middle");
tooltip.attr("dx", 0);
}
}
const path = svg.insert("g", "*")
.attr("fill", "none")
.attr("stroke-opacity", 0.6)
.attr("stroke-width", 1.5)
.selectAll("path")
.data(graph.links)
.join("path")
.attr("stroke", d => d.source.group === d.target.group ? color(d.source.group) : color(d.target.group))
.attr("d", arc);

///////
let highlight = svg.append("g")
.attr("x", margin.left + 4000)
.attr("y", 2000)
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "#333")
.attr("fill-opacity", 1)
.style("font-size", "4vw")
.style("font-weight", 700);
let alias = highlight
.append("text")
.style("font-size", "3vw")
.attr("x", margin.left + 250)
.attr("y", 480)
.attr("dy", "-0.3em");
const overlay = svg.append("g")
.attr("fill", "none")
.attr("pointer-events", "all")
.selectAll("rect")
.data(graph.nodes)
.join("rect")
.attr("width", margin.left + 40)
.attr("height", step)
.attr("y", d => y(d.id) - step / 2)
.on("mouseover", d => {
svg.classed("hover", true);
label.classed("primary", n => n === d);
//label.classed("primary", n => n === d);
//label.classed("secondary_c", n => n === d);
label.style("font-size", function(label_d){ return label_d.id === d.id ? 12 : 10});
// label.selectAll('circle').style("r",function(label_d){return label_d.sourceLinks.length+label_d.targetLinks.length});
// label.classed('primary', n=> n.addTooltip(d3.select(this)));
label.classed("secondary", n => n.sourceLinks.some(l => l.target === d) || n.targetLinks.some(l => l.source === d));
path.classed("primary", l => l.source === d || l.target === d).filter(".primary").raise();
// path.classed("primary", l => l.source === d || l.target === d).filter(".primary").style('stroke', 'firebrick').raise();
alias.text(d.id+ " has "+(d.sourceLinks.length+d.targetLinks.length)+" connection(s) in total" ).attr("fill", "pink");
})
.on("mouseout", d => {
svg.classed("hover", false);
path.classed("primary", false).order();
alias.text("")

});

selector.on('change', function() {
svg.attr("fill", this.value);
})
function update() {
y.domain(graph.nodes.sort(viewof order.value).map(d => d.id));

const t = svg.transition()
.duration(750);

label.transition(t)
.delay((d, i) => i * 20)
.attrTween("transform", d => {
const i = d3.interpolateNumber(d.y, y(d.id));
return t => `translate(${margin.left},${d.y = i(t)})`;
});

path.transition(t)
.duration(750 + graph.nodes.length * 20)
.attrTween("d", d => () => arc(d));

overlay.transition(t)
.delay((d, i) => i * 20)
.attr("y", d => y(d.id) - step / 2);
}

viewof order.addEventListener("input", update);
invalidation.then(() => viewof order.removeEventListener("input", update));

// const container = d3.select(DOM.svg(1000, 300));
const limit = 10;
//const imageLink = 'https://upload.wikimedia.org/wikipedia/commons/4/47/Golf_ball.svg';
const imageHeight = 20
// define some css commands for styling text
/* const styleText = `text {
font: 1.2em sans-serif;
text-anchor: middle;
fill: white;
}` */
// svg.append("style").text(styleText);
const pinkGroup = svg
.append("g")
.attr("transform", () => "translate(" + 600 + "," + 20 + ")")
.attr("id", "pinkGroup")
.attr('fill', '#ff96ca')
/*const greenGroup = svg
.append("g")
.attr("transform", () => "translate(" + 100 + "," + 20 + ")")
.attr("id", "greenGroup")
.attr("fill","lime")*/

/*function init(svg, value) {
svg.attr("value", value);
svg.append("circle")
.attr("r", '20')
svg.append("text")
.text(svg.attr("value"))
.attr("fill", "#ff96ca")
.attr("dy", "0.35em")
// this is code to initialize the rectangles
// we need a dataset of values to bind the rectangles to, from 1 to value
const arrayOfInts = d3.range(1,value+1);
const imageLink2 = 'https://upload.wikimedia.org/wikipedia/commons/4/47/Golf_ball.svg';
console.log(imageLink2)
// this creates rectangles at a constant x position, with y a function of arrayOfInts
// it is very important to create a unique id for each rectangle so we can select them later
svg.selectAll("image")
.data(arrayOfInts)
.enter().append("image")
.attr('xlink:href', imageLink2)
.attr("width", imageHeight)
.attr("height", imageHeight)
.attr("x", -10 )
.attr("y", d => d*imageHeight)
.attr("id", d => svg.attr("id") + "image" + d);
}*/
label.on("mouseover", function(d) {
pinkGroup.attr("value", function(d){return d.sourceLinks.length+d.targetLinks.length});
pinkGroup.append("circle")
.attr("r", '20')
pinkGroup.append("text")
.text(svg.attr("value"))
.attr("fill", "#ff96ca")
.attr("dy", "0.35em")
// this is code to initialize the rectangles
// we need a dataset of values to bind the rectangles to, from 1 to value
const arrayOfInts = d3.range(1,d.sourceLinks.length+d.targetLinks.length+1);
const imageLink2 = 'https://upload.wikimedia.org/wikipedia/commons/4/47/Golf_ball.svg';
console.log(imageLink2)
// this creates rectangles at a constant x position, with y a function of arrayOfInts
// it is very important to create a unique id for each rectangle so we can select them later
pinkGroup.selectAll("image")
.data(arrayOfInts)
.enter().append("image")
.attr('xlink:href', imageLink2)
.attr("width", imageHeight)
.attr("height", imageHeight)
.attr("x", -10 )
.attr("y", d => d*imageHeight)
.attr("id", d => svg.attr("id") + "image" + d);
})
// call the initialization functions
// const score1 = 4
//init(pinkGroup, score1)
//init(greenGroup, limit-3);
function updateScores(svg1) {
let score1 = +svg1.attr("value");
const imageLink2 = 'https://upload.wikimedia.org/wikipedia/commons/4/47/Golf_ball.svg'
// add rectangle to svg1; x value stays constant;
// y is a function of the current value; this grows the rectangle at the bottom
svg1
.append("image").attr('xlink:href', imageLink2)
.attr("width", imageHeight).attr("height", imageHeight)
.attr("x", -10 )
.attr("y", score1*imageHeight)
.attr("id", svg1.attr("id") + "image" + score1);
}
selector.on('change', function() {
if (this.value == "Only same group"){
path.attr("stroke", d=>d.source.group === d.target.group ? color(d.source.group) :"grey");}
else if (this.value == "Only different group"){
path.attr("stroke", d=>d.source.group !== d.target.group ? color(d.source.group) :"grey");}
else if (this.value == "Show all links"){
path.attr("stroke", d=>color(d.source.group));}
})


return div.node()}

//return svg.node();
//}

Insert cell
practice ={
const outerDiv = d3.create("div").attr("id", "outerDiv").attr("height", 1000);
// append a <p></p>
outerDiv.append("p").text("I'm in outer space!");
outerDiv.append("svg").attr("id", "svg1").attr("height", 50)
.append("circle").attr("cx",10).attr("cy", 10).attr("r",10).attr("fill","purple")
}
Insert cell
function arc(d) {
const y1 = d.source.y;
const y2 = d.target.y;
const r = Math.abs(y2 - y1) / 2;
return `M${margin.left},${y1}A${r},${r} 0,0,${y1 < y2 ? 1 : 0} ${margin.left},${y2}`;
}
Insert cell
y = d3.scalePoint(graph.nodes.map(d => d.id).sort(d3.ascending), [margin.top, height - margin.bottom])
Insert cell
margin = ({top: 20, right: 20, bottom: 20, left: 100})
Insert cell
height = (data.nodes.length - 1) * step + margin.top + margin.bottom
Insert cell
step = 14
Insert cell
color = d3.scaleOrdinal(graph.nodes.map(d => d.group).sort(d3.ascending), d3.schemeCategory10)
Insert cell
graph = {
const nodes = data.nodes.map(({id, group}) => ({
id,
sourceLinks: [],
targetLinks: [],
group
}));

const nodeById = new Map(nodes.map(d => [d.id, d]));

const links = data.links.map(({source, target, value}) => ({
source: nodeById.get(source),
target: nodeById.get(target),
value
}));

for (const link of links) {
const {source, target, value} = link;
source.sourceLinks.push(link);
target.targetLinks.push(link);
}

return {nodes, links};
}
Insert cell
data = FileAttachment("miserables.json").json()
Insert cell
d3 = require("d3@5")
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