JSFiddle - React, Tailwind, and code Playground
HTML
<title>D3: Force Layout Test</title>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<body>
</body>
CSS
<style type="text/css">
.d3-tip {
line-height: 1;
padding: 12px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 2px;
font-family: sans-serif;
font-size: 12px;
}
.d3-tip a:link {
color: #ccc;
font-size: 10px;
}
.d3-tip a:visited {
color: #ccc;
}
/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
font-family: sans-serif;
}
/* Style northward tooltips differently */
.d3-tip.n:after {
margin: -1px 0 0 0;
top: 100%;
left: 0;
}
.label {
font-family: sans-serif;
font-size: 12px;
}
</style>
JavaScript
//Width and height
var w = 500;
var h = 500;
//Original data
var graph = {
nodes: [
{ name: "Iamblichus",
location: "Syria",
floruitDate: "290" },
{ name: "Gregory of Nyssa",
location: "Capadocia",
floruitDate: "300" },
{ name: "Melina",
location: "Greece",
floruitDate: "280" },
{ name: "Plotinus",
location: "Rome",
floruitDate: "240" }
],
links: [
{ source: 0, target: 1, relationship: "enemies" },
{ source: 0, target: 2, relationship: "teacher" },
{ source: 1, target: 2, relationship: "teacher" },
{ source: 3, target: 2, relationship: "enemies" }
]
};
var color = d3.scale.category10(); //Sets color for nodes
var fill = d3.scale.category10(); //Sets the color for links
var force = d3.layout.force()
.charge(-250)
.linkDistance(100)
.size([w, h]);
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
var drawGraph = function(graph) {
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke", function(d) {return fill(d.relationship);})
.style("stroke-width", 3);
var gnodes = svg.selectAll('g.gnode')
.data(graph.nodes)
.enter()
.append('g')
.classed('gnode', true);
var node = gnodes.append("circle")
.attr("class", "node")
.attr("r", 20)
.style("fill", function(d, i) { return color(i); })
.call(force.drag);
//Tooltip stuff.
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "Location:" + " " + d.location +
"<br>Floruit Date:" + " " + d.floruitDate;
});
svg.call(tip);
//This is where I'm confused.
node.on('mouseover', tip.show);
...