Standalone LaTeX Document class and TikzPicture

This module contains two Python classes. Firstly, it contains a class Standalone to represent a LaTeX file using the standalone document class.

From its documentation:

The standalone bundle allows users to easily place picture environments or other material in own source files and compile these on their own or as part of a main document. A special standalone class is provided for use with such files, which by default crops the resulting output file to the content. The standalone package enables the user to simply load the standalone files using ``input`` inside a main document.

Secondly, it contains a class TikzPicture which inherits from Standalone that represents a LaTeX file using the standalone document class and containing a tikzpicture.

A Python Module for PGF/Tikz pictures. A TikzPicture object is created from a string starting with r'\begin{tikzpicture}' and ending with r'\end{tikzpicture}'.

The module allows to convert a standalone LaTeX document class file, including tikzpictures, to an image. It allows conversion to pdf, png and svg formats. It also show them automatically in Jupyter using rich representation.

According to wikipedia, PGF/TikZ is a pair of languages for producing vector graphics (e.g., technical illustrations and drawings) from a geometric/algebraic description, with standard features including the drawing of points, lines, arrows, paths, circles, ellipses and polygons.

EXAMPLES:

Standalone LaTeX document class

First Hello World example:

sage: from sage.misc.latex_standalone import Standalone
sage: Standalone('Hello World')
\documentclass{standalone}
\begin{document}
Hello World
\end{document}

Loading a few latex packages:

sage: Standalone('Hello World', usepackage=['amsmath', 'amsfont'])
\documentclass{standalone}
\usepackage{amsmath}
\usepackage{amsfont}
\begin{document}
Hello World
\end{document}

Setting few standalone options (see documentation of standalone for a complete list):

sage: Standalone('Hello World', standalone_config=["border=4mm", "beamer=true"])
\documentclass{standalone}
\standaloneconfig{border=4mm}
\standaloneconfig{beamer=true}
\begin{document}
Hello World
\end{document}

Adding your own list of macros:

sage: Standalone('Hello World', macros=[r'\newcommand{\ZZ}{\mathbb{Z}}'])
\documentclass{standalone}
\newcommand{\ZZ}{\mathbb{Z}}
\begin{document}
Hello World
\end{document}

It provides conversion to images of different format:

sage: from sage.misc.latex_standalone import Standalone
sage: s = Standalone('Hello World')
sage: _ = s.pdf()    # not tested
sage: _ = s.png()    # not tested
sage: _ = s.svg()    # not tested
sage: s              # not tested, in Jupyter, this shows the image directly below the cell

TikzPicture

This module also contains a class TikzPicture which inherits from Standalone to represent more specifically a tikzpicture which is within a standalone document class.

First construct a string describing a tikzpicture:

sage: lines = []
sage: lines.append(r'\begin{tikzpicture}')
sage: lines.append(r'\draw[very thick,orange,->] (0,0) -- (1,1);')
sage: lines.append(r'\end{tikzpicture}')
sage: s = '\n'.join(lines)
sage: print(s)
\begin{tikzpicture}
\draw[very thick,orange,->] (0,0) -- (1,1);
\end{tikzpicture}

One may provide it as input to TikzPicture:

sage: from sage.misc.latex_standalone import TikzPicture
sage: t = TikzPicture(s)

In the terminal, the following shows the content of the standalone document class tex file which contains the tikzpicture. In Jupyter, it shows the picture itself:

sage: t
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\draw[very thick,orange,->] (0,0) -- (1,1);
\end{tikzpicture}
\end{document}

As it is the case for Standalone, the constructor of TikzPicture has many arguments allowing for example to add some more \usepackage lines:

sage: t = TikzPicture(s, usepackage=['amsmath'])
sage: t
\documentclass[tikz]{standalone}
\usepackage{amsmath}
\begin{document}
\begin{tikzpicture}
\draw[very thick,orange,->] (0,0) -- (1,1);
\end{tikzpicture}
\end{document}

Moreover, it allows to load some tikz libraries:

sage: t = TikzPicture(s, usetikzlibrary=['arrows'])
sage: t
\documentclass[tikz]{standalone}
\usetikzlibrary{arrows}
\begin{document}
\begin{tikzpicture}
\draw[very thick,orange,->] (0,0) -- (1,1);
\end{tikzpicture}
\end{document}

The following example illustrates that it works when providing the tikzpicture code generated by Sage from some polyhedron:

sage: from sage.misc.latex_standalone import TikzPicture
sage: V = [[1,0,1],[1,0,0],[1,1,0],[0,0,-1],[0,1,0],[-1,0,0],[0,1,1],[0,0,1],[0,-1,0]]
sage: P = Polyhedron(vertices=V).polar()
sage: s = P.projection().tikz([674,108,-731],112)
sage: t = TikzPicture(s)

Open the image in a viewer (the returned value is a string giving the absolute path to the file in some temporary directory):

sage: path_to_file = t.pdf()                # not tested

Instead, you may save a pdf of the tikzpicture into a file of your choice (but this does not open the viewer):

sage: _ = t.pdf('tikz_polytope.pdf')        # not tested

Opening the image in a viewer can be turned off:

sage: _ = t.pdf(view=False)      # long time (2s) # optional latex

The same can be done with png format (translated from pdf with convert command which needs the installation of imagemagick):

sage: _ = t.png(view=False)      # long time (2s) # optional latex imagemagick

The string representation gives the header (5 lines) and tail (5 lines) of the tikzpicture. In Jupyter, it will instead use rich representation and show the image directly below the cell in png or svg format:

sage: t
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}%
        [x={(0.249656cm, -0.577639cm)},
        y={(0.777700cm, -0.358578cm)},
        z={(-0.576936cm, -0.733318cm)},
...
\node[vertex] at (0.00000, -1.00000, 0.00000)     {};
\node[vertex] at (-0.50000, -0.50000, -0.50000)     {};
%%
%%
\end{tikzpicture}
\end{document}

Use print(t) to see the complete content of the file:

sage: print(t)               # not tested

Adding a border in the options avoids cropping the vertices of a graph:

sage: g = graphs.PetersenGraph()       # optional - sage.graphs
sage: s = latex(g)   # takes 3s but the result is cached # optional latex sage.graphs
sage: t = TikzPicture(s, standalone_config=["border=4mm"], usepackage=['tkz-graph']) # optional latex sage.graphs
sage: _ = t.pdf()    # not tested

The current latex representation of a transducer is a tikzpicture using the tikz library automata. The string can be used as input:

sage: s = latex(transducers.GrayCode())                # optional sage.combinat
sage: t = TikzPicture(s, usetikzlibrary=['automata'])  # optional sage.combinat
sage: _ = t.pdf(view=False)           # long time (2s) # optional sage.combinat latex

AUTHORS:

  • Sébastien Labbé, initial version in slabbe-0.2.spkg, nov 2015.

  • Sébastien Labbé, inclusion into SageMath from slabbe-0.6.2, July 2021.

class sage.misc.latex_standalone.Standalone(content, document_class_options=None, standalone_config=None, usepackage=None, macros=None, use_sage_preamble=False)

Bases: sage.structure.sage_object.SageObject

LaTeX standalone document class.

INPUT:

  • content – string, the content to be added in the document between lines r'\begin{document}' and r'\end{document}'

  • document_class_options – list of strings (default: []), latex document class standalone options. Such options appear on the line \documentclass[...]{standalone} between the brackets.

  • standalone_config – list of strings (default: []), standalone configuration options. Such options are defined with \standaloneconfig{...}

  • usepackage – list of strings (default: []), latex packages.

  • macros – list of strings (default: []), stuff you need for the picture.

  • use_sage_preamble – bool (default: False), whether to include sage latex preamble and sage latex macros, that is, the content of sage.misc.latex.extra_preamble(), sage.misc.latex.extra_macros() and sage.misc.latex_macros.sage_latex_macros().

EXAMPLES:

sage: from sage.misc.latex_standalone import Standalone
sage: content = "\\section{Intro}\nTest\n"
sage: t = Standalone(content)
sage: t
\documentclass{standalone}
\begin{document}
\section{Intro}
Test
\end{document}
sage: t = Standalone(content, standalone_config=["border=4mm"], usepackage=['amsmath'])
sage: t
\documentclass{standalone}
\standaloneconfig{border=4mm}
\usepackage{amsmath}
\begin{document}
\section{Intro}
Test
\end{document}
add_document_class_option(option)

Add a document class option

INPUT:

  • option – string

EXAMPLES:

sage: from sage.misc.latex_standalone import Standalone
sage: t = Standalone('Hello World')
sage: t.add_document_class_option('beamer')
sage: t
\documentclass[beamer]{standalone}
\begin{document}
Hello World
\end{document}
add_macro(macro)

Add a macro

INPUT:

  • macro – string, newcommand line

EXAMPLES:

sage: from sage.misc.latex_standalone import Standalone
sage: t = Standalone('Hello World')
sage: t.add_macro(r'\newcommand{\ZZ}{\mathbb{Z}}')
sage: t
\documentclass{standalone}
\newcommand{\ZZ}{\mathbb{Z}}
\begin{document}
Hello World
\end{document}
add_standalone_config(config)

Add a standalone config

INPUT:

  • config – string

EXAMPLES:

sage: from sage.misc.latex_standalone import Standalone
sage: t = Standalone('Hello World')
sage: t.add_standalone_config("border=4mm")
sage: t
\documentclass{standalone}
\standaloneconfig{border=4mm}
\begin{document}
Hello World
\end{document}
add_usepackage(package)

Add a usepackage line

INPUT:

  • package – string, name of package

EXAMPLES:

sage: from sage.misc.latex_standalone import Standalone
sage: t = Standalone('Hello World')
sage: t.add_usepackage('amsmath')
sage: t
\documentclass{standalone}
\usepackage{amsmath}
\begin{document}
Hello World
\end{document}
content()

Return the content of the standalone document class file

EXAMPLES:

sage: from sage.misc.latex_standalone import Standalone
sage: t = Standalone('Hello World')
sage: t.content()
'Hello World'
sage: from sage.misc.latex_standalone import TikzPicture
sage: s = "\\begin{tikzpicture}\n\\draw (0,0) -- (1,1);\n\\end{tikzpicture}"
sage: t = TikzPicture(s)
sage: print(t.content())
\begin{tikzpicture}
\draw (0,0) -- (1,1);
\end{tikzpicture}
pdf(filename=None, view=True, program=None)

Compiles the latex code with pdflatex and create a pdf file.

INPUT:

  • filename – string (default: None), the output filename. If None, it saves the file in a temporary directory.

  • view – bool (default:True), whether to open the file in a pdf viewer. This option is ignored and automatically set to False if filename is not None.

  • program – string (default:None) 'pdflatex' or 'lualatex'. If None, it uses 'lualatex' if it is available, otherwise 'pdflatex'.

OUTPUT:

string, path to pdf file

EXAMPLES:

sage: from sage.misc.latex_standalone import Standalone
sage: t = Standalone('Hello World')
sage: _ = t.pdf(view=False)     # long time (1s)   # optional latex

Same for instances of TikzPicture:

sage: from sage.misc.latex_standalone import TikzPicture
sage: s = "\\begin{tikzpicture}\n\\draw (0,0) -- (1,1);\n\\end{tikzpicture}"
sage: t = TikzPicture(s)
sage: _ = t.pdf(view=False)     # not tested

A filename may be provided where to save the file, in which case the viewer does not open the file:

sage: from sage.misc.temporary_file import tmp_filename
sage: filename = tmp_filename('temp','.pdf')
sage: path_to_file = t.pdf(filename)   # long time (1s)   # optional latex
sage: path_to_file[-4:]                # long time (fast) # optional latex
'.pdf'

The filename may contain spaces:

sage: filename = tmp_filename('filename with spaces','.pdf')
sage: path_to_file = t.pdf(filename)   # long time (1s)   # optional latex
png(filename=None, density=150, view=True)

Compiles the latex code with pdflatex and converts to a png file.

INPUT:

  • filename – string (default:None), the output filename. If None, it saves the file in a temporary directory.

  • density – integer, (default: 150), horizontal and vertical density of the image

  • view – bool (default:True), whether to open the file in a png viewer. This option is ignored and automatically set to False if filename is not None.

OUTPUT:

string, path to png file

EXAMPLES:

sage: from sage.misc.latex_standalone import Standalone
sage: t = Standalone('Hello World')
sage: _ = t.png(view=False)     # long time (1s)   # optional latex imagemagick

Same for instances of TikzPicture:

sage: from sage.misc.latex_standalone import TikzPicture
sage: s = "\\begin{tikzpicture}\n\\draw (0,0) -- (1,1);\n\\end{tikzpicture}"
sage: t = TikzPicture(s)
sage: _ = t.png(view=False)     # not tested
sage: from sage.misc.temporary_file import tmp_filename
sage: filename = tmp_filename('temp','.png')
sage: path_to_file = t.png(filename) # long time (1s)   # optional latex imagemagick
sage: path_to_file[-4:]              # long time (fast) # optional latex imagemagick
'.png'
svg(filename=None, view=True, program='pdftocairo')

Compiles the latex code with pdflatex and converts to a svg file.

INPUT:

  • filename – string (default:None), the output filename. If None, it saves the file in a temporary directory.

  • view – bool (default:True), whether to open the file in a browser. This option is ignored and automatically set to False if filename is not None.

  • program – string (default:'pdftocairo') 'pdftocairo' or 'pdf2svg'.

OUTPUT:

string, path to svg file

EXAMPLES:

sage: from sage.misc.latex_standalone import Standalone
sage: t = Standalone('Hello World')
sage: _ = t.svg(view=False)     # not tested

Same for instances of TikzPicture:

sage: from sage.misc.latex_standalone import TikzPicture
sage: s = "\\begin{tikzpicture}\n\\draw (0,0) -- (1,1);\n\\end{tikzpicture}"
sage: t = TikzPicture(s)
sage: _ = t.svg(view=False)     # not tested
sage: from sage.misc.temporary_file import tmp_filename
sage: filename = tmp_filename('temp', '.svg')
sage: path_to_file = t.svg(filename, program='pdf2svg')   # long time (1s)   # optional latex pdf2svg
sage: path_to_file[-4:]                                   # long time (fast) # optional latex pdf2svg
'.svg'
sage: path_to_file = t.svg(filename, program='pdftocairo') # long time (1s)   # optional latex pdftocairo
sage: path_to_file[-4:]                                    # long time (fast) # optional latex pdftocairo
'.svg'
tex(filename=None, content_only=False, include_header=None)

Writes the latex code to a file.

INPUT:

  • filename – string (default:None), the output filename. If None, it saves the file in a temporary directory.

  • content_only – bool (default:False) whether to include the header latex part. If True, it prints only the content to the file.

OUTPUT:

string, path to tex file

EXAMPLES:

sage: from sage.misc.latex_standalone import Standalone
sage: t = Standalone('Hello World')
sage: _ = t.tex()
sage: _ = t.tex(content_only=True)

Same for instances of TikzPicture:

sage: from sage.misc.latex_standalone import TikzPicture
sage: s = "\\begin{tikzpicture}\n\\draw (0,0) -- (1,1);\n\\end{tikzpicture}"
sage: t = TikzPicture(s)
sage: _ = t.tex()
sage: _ = t.tex(content_only=True)

Write to a given filename:

sage: from sage.misc.temporary_file import tmp_filename
sage: filename = tmp_filename('temp','.tex')
sage: path_to_file = t.tex(filename)
sage: path_to_file[-4:]
'.tex'
class sage.misc.latex_standalone.TikzPicture(content, standalone_config=None, usepackage=None, usetikzlibrary=None, macros=None, use_sage_preamble=False)

Bases: sage.misc.latex_standalone.Standalone

A TikzPicture embedded in a LaTeX standalone document class.

INPUT:

  • content – string, tikzpicture code starting with r'\begin{tikzpicture}' and ending with r'\end{tikzpicture}'

  • standalone_config – list of strings (default: []), latex document class standalone configuration options.

  • usepackage – list of strings (default: []), latex packages.

  • usetikzlibrary – list of strings (default: []), tikz libraries to use.

  • macros – list of strings (default: []), stuff you need for the picture.

  • use_sage_preamble – bool (default: False), whether to include sage latex preamble and sage latex macros, that is, the content of sage.misc.latex.extra_preamble(), sage.misc.latex.extra_macros() and sage.misc.latex_macros.sage_latex_macros().

EXAMPLES:

Create your own tikz string from scratch and provide it:

sage: from sage.misc.latex_standalone import TikzPicture
sage: lines = []
sage: lines.append(r'\begin{tikzpicture}')
sage: lines.append(r'\draw[very thick,orange,->] (0,0) -- (1,1);')
sage: lines.append(r'\end{tikzpicture}')
sage: s = '\n'.join(lines)
sage: t = TikzPicture(s)
sage: t
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\draw[very thick,orange,->] (0,0) -- (1,1);
\end{tikzpicture}
\end{document}

Then use it by exporting the tikzpicture to other formats, all of the below methods return a string providing the path to the filename, which is by default in a temporary folder:

sage: _ = t.pdf()                     # not tested
sage: _ = t.png()                     # not tested
sage: _ = t.svg()                     # not tested
sage: _ = t.tex()                     # not tested
sage: _ = t.pdf(filename='abc.pdf')   # not tested

Here we create a tikzpicture for the latex representation of a graph. This is using tkz-graph tex library:

sage: g = graphs.PetersenGraph()        # optional sage.graphs
sage: s = latex(g)                      # optional sage.graphs latex
sage: t = TikzPicture(s, standalone_config=["border=4mm"], usepackage=['tkz-graph']) # optional sage.graphs latex
sage: _ = t.pdf(view=False)             # long time (2s) # optional - sage.graphs latex latex_package_tkz_graph

Here are standalone configurations, packages, tikz libraries and macros that can be set:

sage: options = ['preview', 'border=4mm', 'beamer', 'float']
sage: usepackage = ['nicefrac', 'amsmath', 'pifont', 'tikz-3dplot',
....:    'pgfplots']
sage: tikzlib = ['arrows', 'snakes', 'backgrounds', 'patterns',
....:      'matrix', 'shapes', 'fit', 'calc', 'shadows', 'plotmarks',
....:      'positioning', 'pgfplots.groupplots', 'mindmap']
sage: macros = [r'\newcommand{\ZZ}{\mathbb{Z}}']
sage: s = "\\begin{tikzpicture}\n\\draw (0,0) -- (1,1);\n\\end{tikzpicture}"
sage: t = TikzPicture(s, standalone_config=options, usepackage=usepackage,
....:        usetikzlibrary=tikzlib, macros=macros)
sage: _ = t.pdf(view=False)   # long time (2s) # optional latex
add_usetikzlibrary(library)

Add a usetikzlibrary line

INPUT:

  • library – string, name of library

EXAMPLES:

sage: from sage.misc.latex_standalone import TikzPicture
sage: s = "\\begin{tikzpicture}\n\\draw (0,0) -- (1,1);\n\\end{tikzpicture}"
sage: t = TikzPicture(s)
sage: t.add_usetikzlibrary('arrows')
sage: t
\documentclass[tikz]{standalone}
\usetikzlibrary{arrows}
\begin{document}
\begin{tikzpicture}
\draw (0,0) -- (1,1);
\end{tikzpicture}
\end{document}
classmethod from_dot_string(dotdata, prog='dot')

Convert a graph to a tikzpicture using graphviz and dot2tex.

Note

Prerequisite: dot2tex optional Sage package and graphviz must be installed.

INPUT:

  • dotdata – dot format string

  • prog – string (default: 'dot') the program used for the layout corresponding to one of the software of the graphviz suite: ‘dot’, ‘neato’, ‘twopi’, ‘circo’ or ‘fdp’.

EXAMPLES:

sage: from sage.misc.latex_standalone import TikzPicture
sage: G = graphs.PetersenGraph()                  # optional sage.graphs
sage: dotdata = G.graphviz_string()               # optional sage.graphs
sage: tikz = TikzPicture.from_dot_string(dotdata) # optional sage.graphs dot2tex graphviz # long time (3s)
sage: _ = tikz.pdf()      # not tested
sage: dotdata = G.graphviz_string(labels='latex') # optional sage.graphs
sage: tikz = TikzPicture.from_dot_string(dotdata) # optional sage.graphs dot2tex graphviz # long time (3s)
sage: _ = tikz.pdf()      # not tested
sage: W = CoxeterGroup(["A",2])
sage: G = W.cayley_graph()                        # optional sage.graphs
sage: dotdata = G.graphviz_string()               # optional sage.graphs
sage: tikz = TikzPicture.from_dot_string(dotdata) # optional sage.graphs dot2tex graphviz # long time (3s)
sage: _ = tikz.pdf()      # not tested
sage: dotdata = G.graphviz_string(labels='latex') # optional sage.graphs
sage: tikz = TikzPicture.from_dot_string(dotdata) # optional sage.graphs dot2tex graphviz # long time (3s)
sage: _ = tikz.pdf()      # not tested
classmethod from_graph(graph, merge_multiedges=True, merge_label_function=<class 'tuple'>, **kwds)

Convert a graph to a tikzpicture using graphviz and dot2tex.

Note

Prerequisite: dot2tex optional Sage package and graphviz must be installed.

Warning

This method might be deleted in the future in favor of a method in the graph class returning a tikz picture.

INPUT:

  • graph – graph

  • merge_multiedges – bool (default: True), if the graph has multiple edges, whether to merge the multiedges into one single edge

  • merge_label_function – function (default:tuple), a function to apply to each list of labels to be merged. It is ignored if merge_multiedges is not True or if the graph has no multiple edges.

Other inputs are used for latex drawing with dot2tex and graphviz:

  • prog – string (default: 'dot') the program used for the layout corresponding to one of the software of the graphviz suite: ‘dot’, ‘neato’, ‘twopi’, ‘circo’ or ‘fdp’.

  • edge_labels – bool (default: True)

  • color_by_label – bool (default: False)

  • rankdir – string (default: 'down')

  • subgraph_clusters – (default: []) a list of lists of vertices, if supported by the layout engine, nodes belonging to the same cluster subgraph are drawn together, with the entire drawing of the cluster contained within a bounding rectangle.

EXAMPLES:

sage: from sage.misc.latex_standalone import TikzPicture
sage: g = graphs.PetersenGraph()       # optional sage.graphs
sage: tikz = TikzPicture.from_graph(g) # optional sage.graphs dot2tex graphviz
doctest:...: FutureWarning: This class/method/function is marked as experimental.
It, its functionality or its interface might change without a formal deprecation.
See http://trac.sagemath.org/20343 for details.
sage: _ = tikz.pdf()      # not tested

Using prog:

sage: tikz = TikzPicture.from_graph(g, prog='neato', color_by_label=True) # optional sage.graphs dot2tex graphviz # long time (3s)
sage: _ = tikz.pdf()      # not tested

Using rankdir:

sage: tikz = TikzPicture.from_graph(g, rankdir='right') # optional sage.graphs dot2tex graphviz # long time (3s)
sage: _ = tikz.pdf()      # not tested

Using merge_multiedges:

sage: alpha = var('alpha')
sage: m = matrix(2,range(4)); m.set_immutable()
sage: G = DiGraph([(0,1,alpha), (0,1,0), (0,2,9), (0,2,m)], multiedges=True) # optional sage.graphs
sage: tikz = TikzPicture.from_graph(G, merge_multiedges=True) # optional sage.graphs dot2tex graphviz
sage: _ = tikz.pdf()      # not tested

Using merge_multiedges with merge_label_function:

sage: fn = lambda L: LatexExpr(','.join(map(str, L)))
sage: edges = [(0,1,'a'), (0,1,'b'), (0,2,'c'), (0,2,'d')]
sage: G = DiGraph(edges, multiedges=True)       # optional sage.graphs
sage: tikz = TikzPicture.from_graph(G,          # optional sage.graphs dot2tex graphviz
....:           merge_multiedges=True, merge_label_function=fn)
sage: _ = tikz.pdf()      # not tested

Using subgraphs clusters (broken when using labels, see trac ticket #22070):

sage: S = FiniteSetMaps(5)
sage: I = S((0,1,2,3,4))
sage: a = S((0,1,3,0,0))
sage: b = S((0,2,4,1,0))
sage: roots = [I]
sage: succ = lambda v:[v*a,v*b,a*v,b*v]
sage: R = RecursivelyEnumeratedSet(roots, succ)
sage: G = R.to_digraph()                        # optional sage.graphs
sage: G                                         # optional sage.graphs
Looped multi-digraph on 27 vertices
sage: C = G.strongly_connected_components()     # optional sage.graphs
sage: tikz = TikzPicture.from_graph(G,          # optional sage.graphs dot2tex graphviz
....:              merge_multiedges=False, subgraph_clusters=C)
sage: _ = tikz.pdf()      # not tested

An example coming from graphviz_string documentation in SageMath:

sage: f(x) = -1 / x                                       # optional sage.symbolic
sage: g(x) = 1 / (x + 1)                                  # optional sage.symbolic
sage: G = DiGraph()                                       # optional sage.symbolic sage.graphs
sage: G.add_edges((i, f(i), f) for i in (1, 2, 1/2, 1/4)) # optional sage.symbolic sage.graphs
sage: G.add_edges((i, g(i), g) for i in (1, 2, 1/2, 1/4)) # optional sage.symbolic sage.graphs
sage: tikz = TikzPicture.from_graph(G)                    # optional sage.symbolic sage.graphs dot2tex graphviz
sage: _ = tikz.pdf()      # not tested
sage: def edge_options(data):
....:     u, v, label = data
....:     options = {"color": {f: "red", g: "blue"}[label]}
....:     if (u,v) == (1/2, -2): options["label"]       = "coucou"; options["label_style"] = "string"
....:     if (u,v) == (1/2,2/3): options["dot"]         = "x=1,y=2"
....:     if (u,v) == (1,   -1): options["label_style"] = "latex"
....:     if (u,v) == (1,  1/2): options["dir"]         = "back"
....:     return options
sage: tikz = TikzPicture.from_graph(G, edge_options=edge_options)  # optional sage.symbolic sage.graphs dot2tex graphviz
sage: _ = tikz.pdf()      # not tested
classmethod from_graph_with_pos(graph, scale=1, merge_multiedges=True, merge_label_function=<class 'tuple'>)

Convert a graph with positions defined for vertices to a tikzpicture.

Warning

This method might be deleted in the future in favor of a method in the graph class returning a tikz picture.

INPUT:

  • graph – graph (with predefined positions)

  • scale – number (default:1), tikzpicture scale

  • merge_multiedges – bool (default: True), if the graph has multiple edges, whether to merge the multiedges into one single edge

  • merge_label_function – function (default:tuple), a function to apply to each list of labels to be merged. It is ignored if merge_multiedges is not True or if the graph has no multiple edges.

EXAMPLES:

sage: from sage.misc.latex_standalone import TikzPicture
sage: g = graphs.PetersenGraph()                      # optional sage.graphs
sage: tikz = TikzPicture.from_graph_with_pos(g)       # optional sage.graphs
doctest:...: FutureWarning: This class/method/function is marked as experimental.
It, its functionality or its interface might change without a formal deprecation.
See http://trac.sagemath.org/20343 for details.
sage: edges = [(0,0,'a'),(0,1,'b'),(0,1,'c')]
sage: kwds = dict(format='list_of_edges', loops=True, multiedges=True)
sage: G = DiGraph(edges, **kwds)                      # optional sage.graphs
sage: G.set_pos({0:(0,0), 1:(1,0)})                   # optional sage.graphs
sage: f = lambda label:','.join(label)                # optional sage.graphs
sage: TikzPicture.from_graph_with_pos(G, merge_label_function=f) # optional sage.graphs
\documentclass[tikz]{standalone}
\standaloneconfig{border=4mm}
\begin{document}
\begin{tikzpicture}
[auto,scale=1]
% vertices
\node (node_0) at (0, 0) {0};
\node (node_1) at (1, 0) {1};
% edges
\draw[->] (node_0) -- node {b,c} (node_1);
% loops
\draw (node_0) edge [loop above] node {a} ();
\end{tikzpicture}
\end{document}
classmethod from_poset(poset, **kwds)

Convert a poset to a tikzpicture using graphviz and dot2tex.

Note

Prerequisite: dot2tex optional Sage package and graphviz must be installed.

Warning

This method might be deleted in the future in favor of a method in the graph class returning a tikz picture.

INPUT:

  • poset – poset

  • prog – string (default: 'dot') the program used for the layout corresponding to one of the software of the graphviz suite: ‘dot’, ‘neato’, ‘twopi’, ‘circo’ or ‘fdp’.

  • edge_labels – bool (default: True)

  • color_by_label – bool (default: False)

  • rankdir – string (default: 'down')

EXAMPLES:

sage: from sage.misc.latex_standalone import TikzPicture
sage: P = posets.PentagonPoset()       # optional sage.combinat
sage: tikz = TikzPicture.from_poset(P) # optional sage.combinat dot2tex graphviz
doctest:...: FutureWarning: This class/method/function is marked as experimental.
It, its functionality or its interface might change without a formal deprecation.
See http://trac.sagemath.org/20343 for details.
sage: tikz = TikzPicture.from_poset(P, prog='neato', color_by_label=True) # optional sage.combinat dot2tex # long time (3s)
sage: P = posets.SymmetricGroupWeakOrderPoset(4)     # optional sage.combinat
sage: tikz = TikzPicture.from_poset(P)               # optional sage.combinat dot2tex graphviz # long time (4s)
sage: tikz = TikzPicture.from_poset(P, prog='neato') # optional sage.combinat dot2tex graphviz # long time (4s)
tikz_picture_code()

EXAMPLES:

sage: from sage.misc.latex_standalone import TikzPicture
sage: s = "\\begin{tikzpicture}\n\\draw (0,0) -- (1,1);\n\\end{tikzpicture}"
sage: t = TikzPicture(s)
sage: print(t.tikz_picture_code())
\begin{tikzpicture}
\draw (0,0) -- (1,1);
\end{tikzpicture}