Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2@file
3@brief Helper about graphviz.
4"""
5import os
6from ..loghelper import run_cmd
7from .conf_path_tools import find_graphviz_dot
10def plot_graphviz(dot, ax=None, temp_dot=None, temp_img=None, dpi=300):
11 """
12 Plots a dot graph into a :epkg:`matplotlib` plot.
14 @param dot dot language
15 @param ax existing ax
16 @param temp_dot temporary file, if None,
17 a file is created and removed
18 @param temp_img temporary image, if None,
19 a file is created and removed
20 @param dpi dpi
21 @return ax
22 """
23 if temp_dot is None:
24 temp_dot = "temp_%d.dot" % id(dot)
25 clean_dot = True
26 else:
27 clean_dot = False
28 if temp_img is None:
29 temp_img = "temp_%d.png" % id(dot)
30 clean_img = True
31 else:
32 clean_img = False
33 with open(temp_dot, "w", encoding="utf-8") as f:
34 f.write(dot)
35 dot_path = find_graphviz_dot()
36 cmd = '"%s" -Gdpi=%d -Tpng -o "%s" "%s"' % (
37 dot_path, dpi, temp_img, temp_dot)
38 out, err = run_cmd(cmd, wait=True)
39 if err is not None:
40 err = err.strip("\r\n\t ")
41 if len(err) > 0:
42 if clean_dot:
43 os.remove(temp_dot)
44 if clean_img and os.path.exists(temp_img):
45 os.remove(temp_img)
46 raise RuntimeError(
47 "Unable to run command line"
48 "\n---CMD---\n{}\n---OUT---\n{}"
49 "\n---ERR---\n{}".format(
50 cmd, out, err))
51 if ax is None:
52 import matplotlib.pyplot as plt
53 ax = plt.gca()
54 image = plt.imread(temp_img)
55 else:
56 import matplotlib.pyplot as plt
57 image = plt.imread(temp_img)
58 ax.imshow(image)
59 if clean_dot:
60 os.remove(temp_dot)
61 if clean_img and os.path.exists(temp_img):
62 os.remove(temp_img)
63 return ax