Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in NetworkX cannot save a graph as jpg or png file

I have a graph in NetworkX containing some info. After the graph is shown, I want to save it as jpg or png file. I used the matplotlib function savefig but when the image is saved, it does not contain anything. It is just a white image.

Here is a sample code I wrote:

import networkx as nx
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(12,12))
ax = plt.subplot(111)
ax.set_title('Graph - Shapes', fontsize=10)

G = nx.DiGraph()
G.add_node('shape1', level=1)
G.add_node('shape2', level=2)
G.add_node('shape3', level=2)
G.add_node('shape4', level=3)
G.add_edge('shape1', 'shape2')
G.add_edge('shape1', 'shape3')
G.add_edge('shape3', 'shape4')
pos = nx.spring_layout(G)
nx.draw(G, pos, node_size=1500, node_color='yellow', font_size=8, font_weight='bold')

plt.tight_layout()
plt.show()
plt.savefig("Graph.png", format="PNG")

Why is the image saved without anything inside (just white) ?

This is the image saved (just blank): enter image description here

like image 398
Francesco Sgaramella Avatar asked Mar 25 '14 13:03

Francesco Sgaramella


People also ask

How do I show a graph in NetworkX?

Draw the graph G using Matplotlib. Draw the nodes of the graph G. Draw the edges of the graph G. Draw node labels on the graph G.

Can NetworkX handle large graphs?

For NetworkX, a graph with more than 100K nodes may be too large. I'll demonstrate that it can handle a network with 187K nodes in this post, but the centrality calculations were prolonged. Luckily, there are some other packages available to help us with even larger graphs.

How does NetworkX store data?

NetworkX stores graph data in Python objects instantiated from one of several NetworkX classes. You choose the NetworkX class to use based on the type of graph you want to create. NetworkX graph classes include Graph, DiGraph, MultiGraph, and MultiDiGraph.


2 Answers

It's related to plt.show method.

Help of show method:

def show(*args, **kw):
    """
    Display a figure.

    When running in ipython with its pylab mode, display all
    figures and return to the ipython prompt.

    In non-interactive mode, display all figures and block until
    the figures have been closed; in interactive mode it has no
    effect unless figures were created prior to a change from
    non-interactive to interactive mode (not recommended).  In
    that case it displays the figures but does not block.

    A single experimental keyword argument, *block*, may be
    set to True or False to override the blocking behavior
    described above.
    """

When you call plt.show() in your script, it seems something like file object is still open, and plt.savefig method for writing can not read from that stream completely. but there is a block option for plt.show that can change this behavior, so you can use it:

plt.show(block=False)
plt.savefig("Graph.png", format="PNG")

Or just comment it:

# plt.show()
plt.savefig("Graph.png", format="PNG")

Or just save befor show it:

plt.savefig("Graph.png", format="PNG")
plt.show()

Demo: Here

like image 104
Omid Raha Avatar answered Oct 12 '22 22:10

Omid Raha


I struggled with the same problem. Looking at other comments and with the help of this link https://problemsolvingwithpython.com/06-Plotting-with-Matplotlib/06.04-Saving-Plots/ it worked for me! Two things that i had to change in my simple program was to add: %matplotlib inline after importing matplotlib and save the figure before plt.show(). See my basic example:

    #importing the package
    import networkx as nx
    import matplotlib.pyplot as plt
    %matplotlib inline

    #initializing an empty graph
    G = nx.Graph()
    #adding one node
    G.add_node(1)
    #adding a second node
    G.add_node(2)
    #adding an edge between the two nodes (undirected)
    G.add_edge(1,2)

    nx.draw(G, with_labels=True)
    plt.savefig('plotgraph.png', dpi=300, bbox_inches='tight')
    plt.show()

#dpi= specifies how many dots per inch (image resolution) are in the saved image, #bbox_inches='tight' is optional #use plt.show() after saving. Hope this helps.

like image 28
Hema Anjali Avatar answered Oct 12 '22 23:10

Hema Anjali