Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

open .dot formatted graph from python

Tags:

python

dot

As I can plot curves with matplotlib in python, I wonder if there are any ways to show .dot graphs somehow. I have a string describing a graph:

graph name{
1--2;
}

Somehow pass it to a viewer program?

like image 212
gen Avatar asked Feb 15 '23 17:02

gen


1 Answers

Maybe not exactly what you intend to do, but you can use pygraphviz and print your graph to a file:

import pygraphviz as pgv
G=pgv.AGraph()
G.add_edge('1','2')
G.layout()
G.draw('file.png')

(or you can just import a .dot file using G = pgv.AGraph('file.dot'))

Then you can always use Image or openCV to load your file and show it in the viewer.

I don't think pygraphviz allows you to to that directly though.

EDIT:

I recently found out another way and remembered your question: NetworkX lets you do that. Here's how:

Either create your graph using NetworkX directly. It is convenient that most of the commands of NetworkX are the same as those in pygraphviz. Then simply send to matplotlib and plot it there:

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge('1','2')
nx.draw(G)
plt.show()

Or you can import your .dot file through pygraphviz and then transform it into a networkx object:

import pygraphviz as pgv
import networkx as nx
import matplotlib.pyplot as plt
Gtmp = pgv.AGraph('file.dot')
G = nx.Graph(Gtmp)
nx.draw(G)
plt.show()

So now you have more options :)

like image 170
cenna75 Avatar answered Feb 27 '23 11:02

cenna75