Newline in node label in dot (graphviz) language

NewlineGraphvizDot

Newline Problem Overview


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

Newline Solutions


Solution 1 - Newline

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 - Newline

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

Solution 3 - Newline

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 - Newline

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.

Solution 5 - Newline

<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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionM TView Question on Stackoverflow
Solution 1 - NewlinemarapetView Answer on Stackoverflow
Solution 2 - NewlineDmitriyView Answer on Stackoverflow
Solution 3 - NewlineGuillaume JacquenotView Answer on Stackoverflow
Solution 4 - NewlinebbartleyView Answer on Stackoverflow
Solution 5 - NewlineJan PokornýView Answer on Stackoverflow