0

Recently I asked the question How to represent graphs with ipython. The answer was exactly what i was looking for, but today i'm looking for a way to show the edge valuation on the final picture.

The edge valuation is added like this :

import networkx as nx
from nxpd import draw # If another library do the same or nearly the same
                      # output of nxpd and answer to the question, that's
                      # not an issue
import random

G = nx.Graph()
G.add_nodes_from([1,2])
G.add_edge(1, 2, weight=random.randint(1, 10))

draw(G, show='ipynb')

And the result is here.

Result provided by ipython notebook

I read the help of nxpd.draw (didn't see any web documentation), but i didn't find anything. Is there a way to print the edge value ?

EDIT : also, if there's a way to give a formating function, this could be good. For example :

def edge_formater(graph, edge):
    return "My edge %s" % graph.get_edge_value(edge[0], edge[1], "weight")

EDIT2 : If there's another library than nxpd doing nearly the same output, it's not an issue

EDIT3 : has to work with nx.{Graph|DiGraph|MultiGraph|MultiDiGraph}

Community
  • 1
  • 1
FunkySayu
  • 7,641
  • 10
  • 38
  • 61

1 Answers1

1

If you look at the source nxpd.draw (function draw_pydot) calls to_pydot which filters the graph attributes like:

if attr_type == 'edge':
    accepted = pydot.EDGE_ATTRIBUTES
elif attr_type == 'graph':
    accepted = pydot.GRAPH_ATTRIBUTES
elif attr_type == 'node':
    accepted = pydot.NODE_ATTRIBUTES
else:
    raise Exception("Invalid attr_type.")

d = dict( [(k,v) for (k,v) in attrs.items() if k in accepted] )

If you look up pydot you find the pydot.EDGE_ATTRIBUTES which contains valid Graphviz-attributes. The weight strictly refers to edge-weight by Graphviz if I recall, and label is probably the attribute you need. Try:

G = nx.Graph()
G.add_nodes_from([1,2])
weight=random.randint(1, 10)
G.add_edge(1, 2, weight=weight, label=str(weight))

Note that I haven't been able to test if this works, just downvote if it doesn't.

RickardSjogren
  • 4,070
  • 3
  • 17
  • 26