JSFiddle - React, Tailwind, and code Playground

by wadefagen

HTML

<script src="http://d3js.org/d3.v3.min.js"></script>
<div id="chart"></div>

CSS

.chart {
    height: 500px;
    width: 800px;
}

.node {
  stroke: #fff;
  stroke-width: 1.5px;
}

.link {
  stroke: #999;
  stroke-opacity: .6;
}

JavaScript

var majors = [
  /* [0]: */ { major: "CS" },
  /* [1]: */ { major: "Informations" },
  /* [2]: */ { major: "Accounting" },
  /* [3]: */ { major: "Finance" }
];

var overlaps = [
  /* CS -> Info */ { source: 0, target: 1, overlap: 3 },
  /* CS -> Accy: No overlap, no edge needed */
  /* CS -> Fin: No overlap, no edge needed */

  /* Info -> Accy */ { source: 1, target: 2, overlap: 1 },
  /* Info -> Fin */  { source: 1, target: 3, overlap: 1 },
  
  /* Info -> Fin */  { source: 2, target: 3, overlap: 12 }
];



var width = 800, height = 500;

var svg = d3.select("#chart")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

var force = d3.layout.force()
    .size([width, height])
    .nodes(majors)
    .links(overlaps)
    .start();


/* Draws circles for each major */
var node = svg.selectAll(".node")
    .data(majors)  // <-- Data is majors array of objects
    .enter()
    .append("circle")
    .attr("class", "node")
    .attr("r", "5")
    .style("fill", "blue");

/* Sets up lines to link between the majors */
var link = svg.selectAll(".link")
    .data(overlaps)  // <-- Data is overlaps array of objects
    .enter()
    .append("line")
    .attr("class", "link")
	// Since our data is the overlaps, d is an overlap:
	//   d.source (Number)
	//   d.target (Number)
	//   d.overlap (Number)
    .style("stroke-width", function(d) { return d.overlap; });

/* Connection between simulation and visualization */
force.on("tick", function() {
    // Every tick of our simulation, change where our
    // lines start/end (x1, y1) -> (x2, y2):
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    // Every tick of our simulation, change where our
    // circles are positioned:
    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
});