Search code examples
pythonmatplotlibgraphvizgraphic

Arched Relationship Infographic In Python


This is a very specific inforgraphic challange altough the fundemental question is how do you build archs between words using matplotlib, cario or an other python libary.

Given a the following data structure.

me, you, 7 | me, apple, 9 | apple, you, 1 | bike, me, 5

Names would be displayed horizontally the names with the most relationships larger than the others and then there would be weighted archs between the names. A 10 weighted arch would be twice as thick as a 5 weighted arch.

Inspiration comes from: similar diverstiy. http://similardiversity.net/

Let the challange commence!


Solution

  • There are several libraries, at least one of which relies on Matplotlib, that will do what you want. I recommend Networkx (www.networkx.lanl.gov) to build your graph structure, and which you can then use to call the relevant Matplotlib methods to plot. Networkx and Matplotlib work very well together.

    import networkx as NX
    import matplotlib.pyplot as PLT
    Gh = NX.Graph()
    Gh.add_edge("You", "Bike", weight=1.0)
    Gh.add_edge("Bike", "Apple", weight=0.9)
    Gh.add_edge("Me", "Bike", weight=1.1)
    all_nodes = Gh.nodes()
    # to scale node size with degree:
    scaled_node_size = lambda(node) : NX.degree(Gh, node) * 700
    position = NX.spring_layout(Gh)    # just choose a layout scheme
    NX.draw_networkx_nodes(Gh, position, node_size=map(scaled_node_size, all_nodes))
    NX.draw_network_edges(Gh, position, Gh.edges(), width=1.0, alpha=1.0, edge_color="red")
    # now for the Matplotlib part:
    PLT.axis("off")
    PLT.show()
    

    As you can see, you could scale the edges by applying a factor to vary the 'weight' parameter to any of the 'edge' methods, just the same way as i did it for node scaling.

    I would also recommend pygraphviz (obviously using graphviz as its backend). It is very similar to Netwworkx (same lead developer).