Newline in node label in dot (graphviz) language

Does anyone know how to put newline in the label of the node? \n is not working - instead some new nodes appear.


Solution 1:

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.

Solution 2:

Try "\\n" that works: dot.node('test', label="line1\\nline2").

Solution 3:

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"]
}

Solution 4:

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.