pythonnetworkxgraph-coloring

How to force some nodes to be a particular color in networkX


I want to color the nodes of a networkx graph, but I also want to have the ability to force a set of nodes to be a particular color while still being able to color the whole all the nodes in the graph properly. Does anyone have an idea of how to do this?


Solution

  • Your simplest solution might be to just look at the definition of greedy_color in greedy_coloring.py and copy it with modifications. If you're not using interchange, the code is really quite simple.

    All it does is traverse the nodes in some order determined by the strategy. For each node, it assigns it the smallest color not yet assigned to any of its edges.

    You would just need to change the colors = {} initialization to be whatever coloring you've already chosen for the initial nodes, and then in the loop a few lines below it, ignore any nodes u that were part of your initial set. (Just test if u in colors: continue).