Search code examples
matplotlibgraph-tool

Make coordinate systems agree between matplotlib and graph-tool


Very conveniently, graph-tool.draw.graph_draw lets you specify a matplotlib Axes object as a canvas for drawing. Not so conveniently, the coordinate systems don't line up. The following script demonstrates the issue. Is there an easier fix than manually reversing the coordinates given to one or the other?

import matplotlib
matplotlib.use('cairo')
from matplotlib import pyplot
import graph_tool.all

x = [0, 1]
y = [0, 1]

g = graph_tool.Graph()
pos = g.new_vertex_property('vector<float>')
v_0 = g.add_vertex()
v_1 = g.add_vertex()
g.add_edge(u, v)
pos[v_0] = [0,0]
pos[v_1] = [1,1]

pyplot.plot(x, y)
ax = pyplot.gca()
graph_tool.draw.graph_draw(g, pos=pos, mplfig=ax)
pyplot.savefig('flip.png')

script result


Solution

  • This is a bug. It has been fixed now in the current git version. In the meantime, you have to flip the coordinates manually, with:

        x, y = ungroup_vector_property(pos, [0, 1])
        y.fa *= -1
        y.fa -= y.fa.min()
        pos = group_vector_property([x, y])