Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw multiple python-igraph graphs from single jupyter/ipython cell

Similarly to this question, I wanted to draw multiple graphs from a single ipython-notebook cell with the following code:

[1]:
%matplotlib inline
import igraph # it is `pip install python-igraph` on py2
import matplotlib.pyplot as plt
import numpy as np

[2]:
# draws a graph successfully
igraph.plot(igraph.Graph.Erdos_Renyi(10, .5))

[3]:
for p in np.arange(.3, .8, .1):
    g = igraph.Graph.Erdos_Renyi(10, p)
    igraph.plot(g)

How can I show multiple graphs from [3] cell on a notebook?

It seems I could use this solution if I wanted to draw some matplotlib charts like this:

[4]:
for p in np.arange(.3, .8, .1):
    g = igraph.Graph.Erdos_Renyi(10, p)
    plt.loglog(sorted(g.degree(), reverse=True), marker='o')
    plt.show()

But this is not applicable to igraph graphs AFAICS. Is there some way to convert igraph.drawing.Plot to a more matplotlib familiar object?

like image 373
Ebrahim Byagowi Avatar asked Jan 04 '23 18:01

Ebrahim Byagowi


2 Answers

I ended up to a solution like this:

from IPython.core.display import display, SVG

for p in np.arange(.3, .8, .1):
    g = igraph.Graph.Erdos_Renyi(10, p)
    print(p)
    display(SVG(igraph.plot(g)._repr_svg_()))

Same can be used for any object that supports _repr_svg_() or _repr_png_() so this is not python-igraph limited so far.

like image 68
Ebrahim Byagowi Avatar answered Jan 12 '23 03:01

Ebrahim Byagowi


I'm using igraph 0.8.2 and Python 3.7. The above answer didn't work for me:

TypeError: a bytes-like object is required, not 'tuple'

I've found another way to do it using temporary file and reading an image from it:

import os
from IPython.display import display, Image

for p in np.arange(.3, .8, .1):
    g = ig.Graph.Erdos_Renyi(10, p)
    ig.plot(g).save('temporary.png') 
    display(Image(filename='temporary.png'))
    os.remove('temporary.png')
like image 23
mathfux Avatar answered Jan 12 '23 02:01

mathfux