How to save a dependency graph as image in NLTK Python

786 Views Asked by At

I found a few posts including this one on how to generate a dependency graph. However, I'm looking for an option to export a dependency graph as a PNG/SVG image.

For simplicity, let's assume we already parsed a sentence The quick brown fox jumps over the lazy dog. and we have the output in to_conll(4) format. Now if pass this result to the DependencyGrpah class

from nltk.parse import DependencyGraph
DependencyGraph(
'''The  DT  4   det
quick   JJ  4   amod
brown   JJ  4   amod
fox NN  5   nsubj
jumps   VBZ 0   ROOT
over    IN  9   case
the DT  9   det
lazy    JJ  9   amod
dog NN  5   obl
.   .   5   punct'''
)

It produces the following the image

dependency graph in nltk

My question is how can I save this image as a PNG/SVG file?

3

There are 3 best solutions below

4
On

You can convert it from a .ps to a .png.

import os
from nltk.draw.tree import TreeView

TreeView(GRAPH)._cframe.print_to_file('tree.ps')
os.system('convert tree.ps tree.png')
0
On

If you are using VScode to experiment with notebook files, there is a small icon at the right upper corner. then there will be an icon in the right upper corner to save your graph.

1
On

You can use the method to_dot() on your DataGraph object, and then proceed to create a Graphviz object from raw and then save it into a file with render.

You can choose both the filename and the format (png, pdf...), as reported in the method signature