igraph / python-igraph

Python interface for igraph
GNU General Public License v2.0
1.31k stars 249 forks source link

I cannot plot graph with labels with matplotlib #510

Closed Lebsasha closed 2 years ago

Lebsasha commented 2 years ago

I cannot plot graph with labels with matplotlib

Suppose the following example code.

import matplotlib.pyplot as plt
import igraph as ig

g = ig.Graph([(2, 3), (3, 4), (4, 5), (5, 3)])
g.vs["label"] = ["0", "1", "2", "3", "4", "5"]
g.vs["name"] = ["0", "1", "2", "3", "4", "5"]  # I'm not sure if I need this line, but just in case, let it be

fig, ax = plt.subplots()
layout = g.layout("kk")
ig.plot(g, layout=layout, bbox=(300, 300), margin=20, target=ax)
plt.show()

When I run this code, the following image without labels is obtained. image

If I run the same code without passing the option target=ax, then I obtain the image with labels, but as far as I know, it plots via cairo, not matplotlib. But for some reason, I need to plot graph with matplotlib I have Igraph 0.9.9 installed by pip, matplotlib 3.5.1, pycairo 1.16.2, cairocffi 1.3.0, Python 3.7.3, Linux Debian 10.

iosonofabio commented 2 years ago

Matplotlib plotting has improved a lot in the develop branch which will be released as 0.10. until then, I'd recommend just plotting the vertex labels using a for loop of ax.text commands.

Lebsasha commented 2 years ago

Thank you @iosonofabio! If somewho, like I, faced with this problem before releasing version 0.10, I post code for doing this

import matplotlib.pyplot as plt
import igraph as ig

g = ig.Graph([(2, 3), (3, 4), (4, 5), (5, 3)])
g.vs["label"] = ["0", "1", "2", "3", "4", "5"]

fig, ax = plt.subplots(constrained_layout=True)
layout = g.layout_kamada_kawai()
ig.plot(g, layout=layout, target=ax)
x_length = ax.viewLim.xmax - ax.viewLim.xmin  # same as x_length = ax.get_xlim()[1] - ax.get_xlim()[0]
y_length = ax.viewLim.ymax - ax.viewLim.ymin  # same as y_length = ax.get_ylim()[1] - ax.get_ylim()[0]
for i, coord in enumerate(layout.coords):
    ax.text(coord[0]+0.01*x_length, coord[1]-0.01*y_length, g.vs["label"][i], verticalalignment='top', fontsize='large')
plt.show()

It produces following graph with labels image

iosonofabio commented 2 years ago

yep, that's the poor man's version :smirk:

Thanks @Lebsasha

stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. Thank you for your contributions.