1

I have the attached code to great a pydot graph and I would like one of the labels to have subscript. I tried the following but it just renders it as Y<SUB>2</SUB>. How can I obtain it with subscript?

import pydot

graph = pydot.Dot(graph_type='digraph', rankdir="LR")
# add node
graph.add_node(pydot.Node('X', label='X'))
graph.add_node(pydot.Node('Y', label='Y<SUB>2</SUB>'))

# add edege
graph.add_edge(pydot.Edge('X', 'Y'))
graph.write_png("mygraph.png")
Tom Ron
  • 5,906
  • 3
  • 22
  • 38

2 Answers2

2

If you have LaTex set up in your environment you can do this using LaTex markup for your graph. You will have to pass the resulting graph through LaTex so will need the dot2tex tool https://dot2tex.readthedocs.io/en/latest/.

graph.add_node(pydot.Node('Y', label='$Y_{2}$'))
Jon Guiton
  • 1,360
  • 1
  • 9
  • 11
  • Unfortunately, it looks like dot2tex escapes all useful character so that we end up with latex code that looks like this: [draw,ellipse] {\\$Y\\_\\{2\\}\\$};\n – Tobbey May 07 '20 at 14:01
1

Although it might have been obvious to some, an actual answer to the question could be:

import dot2tex
import pydot

graph = pydot.Dot(graph_type='digraph', rankdir="LR")
# add node
graph.add_node(pydot.Node('X', label='X'))
#graph.add_node(pydot.Node('Y', label='Y<SUB>2</SUB>'))
graph.add_node(pydot.Node('Y', label='$$Y_{2}$$'))

# add edege
graph.add_edge(pydot.Edge('X', 'Y'))
#graph.write_png("mygraph.png")

# Export to tex
texcode = dot2tex.dot2tex(graph.to_string(),format='tikz',texmode='math',crop=True)
with open("test.tex", "w") as f: 
    f.write(texcode) 

Then generate pdf with

pdflatex ./test.tex
Tobbey
  • 469
  • 1
  • 4
  • 18