pythonplotnetworkxedges

How to make networkx edge label "hitbox" transparant?


How can one reduce the size of the white space around an edge label in networkx, or even make it fully transparent whilst preserving the edge weight font size?

As an example of the behaviour, one can look at edge-weight -24 from node rand_1_1 to node degree_receiver_2_1_1, which also interferes with the edge from the node degree_receiver_0_1_0 to node degree_receiver_2_1_1 (even though the -24 does not really touch that edge): enter image description here

To create the edge weights in the first place I am using the following function:

def get_edge_labels(node_labels_dict:Dict,snn_graph:nx.DiGraph,pos:Any):
    """Sets the edge labels. pos is node position."""
    edge_labels:Dict={}
    
    # Get the synaptic weights per node.
    for edge in snn_graph.edges:
        edgeweight=snn_graph.edges[edge]["synapse"].weight
        
        # Create dictionary with synaptic weights.
        edge_labels[edge]=edgeweight
        
    nx.draw_networkx_labels(snn_graph, pos, labels=node_labels_dict)
    
    # TODO: Set edge weight positions per edge to non-overlapping positions.
    # TODO: Make edge weight "hitbox" transparant.
    nx.draw_networkx_edge_labels(snn_graph, pos, edge_labels, font_size=5, label_pos=0.2)

Solution

  • The background is specified by the bbox parameter. The default is {boxstyle=’round’, ec=(1.0, 1.0, 1.0), fc=(1.0, 1.0, 1.0)}. To make the box transparent, supply an additional alpha parameter set to zero: {boxstyle=’round’, ec=(1.0, 1.0, 1.0), fc=(1.0, 1.0, 1.0), alpha=0}, i.e.:

    nx.draw_networkx_edge_labels(snn_graph, ..., bbox={boxstyle=’round’, ec=(1.0, 1.0, 1.0), fc=(1.0, 1.0, 1.0), alpha=0})