I'm using d3 to generate a force-directed graph based on this example: Force-directed graph example in d3
I'm implementing this in combination with React, in which d3 forces the directed graph and reactjs renders the visualization.
Now I would like to style (color) the nodes based on the groups they are assigned to. This is my data for the nodes:
var nodes = [
{"name":"node1","group":"2"},
{"name":"node2","group":"4"},
{"name":"node3","group":"5"}]
In this example, they actually do the exact same thing, except without reactjs. However, I couldn't find any clear way to do this in combination with reactjs.
Ideally graphing library such as d3.js, plotly.js takes just layout and data. Color assignment to separate node is done internally. However, you can accomplish it by doing this:
Assuming this is your data:
const nodes = [{
"name": "Vertex 5",
"group": "1"
},
{
"name": "Vertex 9",
"group": "4"
},
{
"name": "Vertex 15",
"group": "5"
}
];
You need to use the d3 api to create a mapping between your groups and the colors. You can do this by adding the following to your component that creates the nodes:
var color = d3.scaleOrdinal(d3.schemeCategory10);
Then you can pass this mapping to the component which is responsible for creating your directed graph, i.e. in your case in the render method:
fill={color(d.group)}
This tells the fill attribute to get the filling from the mapping in the variable color, looking at every node via the variable d.