Does anyone know how to put newline in the label of the node? \n is not working - instead some new nodes appear.
5 Answers
This works for me as documented:
digraph {
n[label="two\nlines"]
"on\nthree\nlines"
}
Either put in in a label attribute (my preference), or use it as the node's name, but always enclose it with double quotes.
You can use \n character
With graphviz package, this would give
from graphviz import Digraph
d=Digraph()
d.node('test',label='line 1\\nline 2')
print(d.source)
This would give
digraph {
test [label="line 1\nline 2"]
}
<BR/> tag in a HTML-like label creates a line break.
digraph {
n[label=<two<BR/>lines>]
}
This can come handy when the \n syntax cannot be used. Most notably, the graphviz package for LaTeX can have problems parsing \ inside .tex files, and using the HTML-like syntax is a workaround.
This issue was also important to me, as I was using graphviz to generate detailed UML diagrams and needed to use escape characters in the labels. However, using the Python package, I encountered a bug in how escape characters are handled, so some of the recommended solutions did not work.
For example:
from graphviz import Digraph
d=Digraph()
d.node('test',label='line 1\\nline 2')
print(d.source)
Generated the following (note that escaping does not work):
digraph {
test [label="line 1\\nline 2"]
}
Workarounds such as using a single backslash, rawstrings, are infuriatingly ineffective. However, the workaround that did ultimately work was the following:
s = graphviz.Source(d.source.replace('\\\\', '\\'))
s.render('my_uml')
I don't know if this bug in handling escape characters is in the Python bindings (v0.12) or graphviz itself (v2.44), but since others may encounter it, I wanted to offer this solution.
\n. - Andrew