Accepted answer

First of all, I'd recommend you to read the this documentation that could provide you with some insights on how to manage colors with d3.js.

Actually you have all the required information in your JSON. So firstly you should create your scale object. Here is an example using the data provided in your JSON.

var myData = ["Low","Medium","High","Very High"];

// Defining colors
var color = d3.scaleOrdinal()
  .range(["#009a44","#eaaa00","#f68d2e","#bc204b"]) // Your data
  .unknown('black') // Fallback solution

After that you should apply this object to your d3 structure in some similar manner:

  ... // Here goes your svg structure creation
  .style('fill', function(d) { // Applying your original scale
    return color(;

Here you can find a complete example of your node graph with legend

var myData = ["Low","Medium","High","Very High"];

var graph = {
  "nodes": [
    {"id": "Myriel", "group": 'Low'},
    {"id": "Napoleon", "group": 'Low'},
    {"id": "Mlle", "group": 'Medium'},
    {"id": "Mme", "group": 'Medium'},
    {"id": "CountessdeLo", "group": 'High'},
    {"id": "Geborand", "group": 'Very High'},
    {"id": "Champtercier", "group": 'Very High'},
    {"id": "Cravatte", "group": 'Random'},
  "links": [

var svg ="svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

// Defining colors
var color = d3.scaleOrdinal()
  .range(["#009a44","#eaaa00","#f68d2e","#bc204b"]) // Your data
  .unknown('black') // Fallback solution

var linearScale = d3.scaleLinear()
	.domain([0, myData.length - 1])
	.range([0, 100]);

var simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) { return; }))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2));

  var link = svg.append("g")
      .attr("class", "links")
      .attr("stroke-width", function(d) { return Math.sqrt(d.value); });

  var node = svg.append("g")
      .attr("class", "nodes")
  var circles = node.append("circle")
      .attr("r", 20)
      .attr("fill", function(d) { return color(; });

      .on("tick", ticked);


  function ticked() {
        .attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return; })
        .attr("y2", function(d) { return; });

        .attr("transform", function(d) {
          return "translate(" + d.x + "," + d.y + ")";
	.attr('y', function(d, i) {
		return linearScale(i);
	.text(function(d) {
		return d;
	.style('fill', function(d) {
		return color(d);
.links line {
  stroke: #999;
  stroke-opacity: 0.6;

.nodes circle {
  stroke: #fff;
  stroke-width: 1.5px;

text {
  font-family: sans-serif;
  font-size: 10px;
<script src=""></script>
<svg width="960" height="600">
  <g id="wrapper" transform="translate(100, 40)">

Please, let me know if my answer is not clear for you or you need some additional information or help.

Related Query