Search code examples
pythonnetworkxgraphviz

Networkx DiGraph nodes, set the border and inner color and format text


I'm using Django, and in my view I generate a diagram of relations between parties. The problem is with the following:

nx.set_node_attributes(G, fill_coloring, name="background")

But this unfortunately doesn't work. I'm unable to find in the documentation how I can set it properly. What I want to achieve is to direct the coloring / formatting of each node based on masterdata related to it.

nx.set_node_attributes(G, border_coloring, name="color")

With the above I'm able to set the border color, but not the inner color. What am I overlooking?

Ideally later on by adding information to the lines etc., but for now I want to color the nodes themselves in specific colors. Currently, it only colors the border. What am I overlooking / misunderstanding?

def index(request):

    filename = f'{datetime.now():%Y-%m-%d_%H-%M-%S}.png'
    save_path = 'static/app/master/routing/'
    completeName = os.path.join(save_path, filename)
    print(completeName)

    G = nx.DiGraph()

    routings = Customer_Routing.objects.all()

    end_customers = []
    border_coloring = {}
    fill_coloring = {}

    for e in routings:
        G.add_edge(e.customer_start.name, e.customer_end.name)
        if e.customer_end.end_customer == True:
            try:
                print(e.customer_end.customer_class.name)
                if e.customer_end.customer_class.name == "DIY":
                    border_coloring[e.customer_end.name] = "#DAC85A"
                    fill_coloring[e.customer_end.name] = "#FEF19C"

            except AttributeError:
                print(e.customer_end.name + " has no class.")
    
    ### Define the customer coloring
    nx.set_node_attributes(G, border_coloring, name="color")
    nx.set_node_attributes(G, fill_coloring, name="background")

    A = to_agraph(G)
    A.draw(completeName, prog='dot')

    template = loader.get_template('index.html')
    context = {
        'img': completeName,
        'routing': routings,
    }
    return HttpResponse(template.render(context, request))

EDIT: I found the answer, shortly after posting this. Graphviz needs the style to be set to "filled".

Below solved this:

nx.set_node_attributes(G, {e.customer_end.name: "filled"}, name="style")

Solution

  • Thanks @Paul Brodersen; below posted as accepted answer:

    I found the answer, shortly after posting this. Graphviz needs the style to be set to "filled".

    Below solved this:

    nx.set_node_attributes(G, {e.customer_end.name: "filled"}, name="style")
    

    Additionally I changed the model to add colors based on the segmentation. Now the for looks as follows:

    nx.set_node_attributes(G, {e.customer_end.name: "filled"}, name="style")
    border_coloring[e.customer_end.name] = e.customer_end.customer_segment.border_color
    fill_coloring[e.customer_end.name] = e.customer_end.customer_segment.fill_color