Tikz Picture

TikzPicture

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

The module allows easy creation of tikz pictures from Sage objects like graphs and posets. Conversion of tikz pictures to pdf and png format based on standalone LaTeX document class.

EXAMPLES:

sage: from slabbe 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)

Creation of a pdf in a temporary directory. The returned value is a string giving the file path:

sage: path_to_file = t.pdf(view=False)   # long time (2s)

Setting view=True, which is the default, opens the pdf in a viewer.

sage: t
\documentclass[tikz]{standalone}
\usepackage{amsmath}
\begin{document}
\begin{tikzpicture}%
        [x={(0.249656cm, -0.577639cm)},
        y={(0.777700cm, -0.358578cm)},
        z={(-0.576936cm, -0.733318cm)},
        scale=2.000000,
...
... 80 lines not printed (4889 characters in total) ...
...
\node[vertex] at (1.00000, 1.00000, -1.00000)     {};
\node[vertex] at (1.00000, 1.00000, 1.00000)     {};
%%
%%
\end{tikzpicture}
\end{document}

Use print t to see the complete content of the file.

Adding a border avoids croping the vertices of a graph:

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

If dot2tex Sage optional package and graphviz are installed, then the following one liner works:

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

AUTHORS:

  • Sébastien Labbé, initial version in slabbe-0.2.spkg, nov 2015.
class slabbe.tikz_picture.StandaloneTex(content, standalone_options=None, usepackage=['amsmath'], usetikzlibrary=None, macros=None, use_sage_preamble=False)

Bases: sage.structure.sage_object.SageObject

See the class documentation for full information.

EXAMPLES:

sage: from slabbe import StandaloneTex
sage: content = "\\section{Intro}\n\nTest\n"
sage: t = StandaloneTex(content)
sage: from slabbe import TikzPicture
sage: s = "\\begin{tikzpicture}\n\\draw (0,0) -- (1,1);\n\\end{tikzpicture}"
sage: t = TikzPicture(s)
content()

EXAMPLES:

sage: from slabbe 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}
pdf(filename=None, view=True)

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.

OUTPUT:

string, path to pdf file

EXAMPLES:

sage: from slabbe 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)
sage: _ = t.pdf()    # not tested
sage: from sage.misc.temporary_file import tmp_filename
sage: filename = tmp_filename('temp','.pdf')
sage: _ = t.pdf(filename)   # long time (2s)

ACKNOWLEDGEMENT:

The code was adapted and taken from the module sage.misc.latex.py.
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 slabbe 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)
sage: _ = t.png()    # not tested
sage: from sage.misc.temporary_file import tmp_filename
sage: filename = tmp_filename('temp','.png')
sage: _ = t.png(filename)      # long time (2s)

ACKNOWLEDGEMENT:

The code was adapted and taken from the module sage.misc.latex.py.
svg(filename=None, view=True)

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.

OUTPUT:

string, path to svg file

EXAMPLES:

sage: from slabbe 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)
sage: _ = t.svg()    # not tested
sage: from sage.misc.temporary_file import tmp_filename
sage: filename = tmp_filename('temp','.svg')
sage: _ = t.svg(filename)      # long time (2s)

ACKNOWLEDGEMENT:

The code was adapted and taken from the module sage.misc.latex.py.
tex(filename=None, include_header=True)

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.
  • include_header – bool (default:True) whether to include the header latex part. If False, it prints only the tikzpicture part to the file.

OUTPUT:

string, path to tex file

EXAMPLES:

sage: from slabbe 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)
sage: _ = t.tex()

Write only the tikzpicture without header and begin/end document:

sage: _ = t.tex(include_header=False)

Write to a given filename:

sage: from sage.misc.temporary_file import tmp_filename
sage: filename = tmp_filename('temp','.tex')
sage: _ = t.tex(filename)
class slabbe.tikz_picture.TikzPicture(content, standalone_options=None, usepackage=['amsmath'], usetikzlibrary=None, macros=None, use_sage_preamble=False)

Bases: slabbe.tikz_picture.StandaloneTex

Creates a TikzPicture embedded in a LaTeX standalone document class.

INPUT:

  • code – string, tikzpicture code starting with r'\begin{tikzpicture}' and ending with r'\end{tikzpicture}'
  • standalone_options – list of strings (default: []), latex document class standalone configuration options.
  • usepackage – list of strings (default: ['amsmath']), 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:

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

Here are standalone configurations, packages, tikz libraries and macros you may want to set:

sage: options = ['preview', 'border=4mm', 'beamer', 'float']
sage: usepackage = ['nicefrac', 'amsmath', 'pifont', 'tikz-3dplot',
....:    'tkz-graph', 'tkz-berge', '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_options=options, usepackage=usepackage, 
....:        usetikzlibrary=tikzlib, macros=macros)
sage: _ = t.pdf(view=False)   # long time (2s)
classmethod from_graph(graph, merge_multiedges=True, merge_label_function=<type 'tuple'>, **kwds)

Convert a graph to a tikzpicture using graphviz and dot2tex.

Note

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

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 slabbe import TikzPicture
sage: g = graphs.PetersenGraph()
sage: tikz = TikzPicture.from_graph(g) # optional dot2tex # long time (3s)
sage: _ = tikz.pdf()      # not tested

Using prog:

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

Using rankdir:

sage: tikz = TikzPicture.from_graph(g, rankdir='right') # optional dot2tex # 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)
sage: tikz = TikzPicture.from_graph(G, merge_multiedges=True) # optional dot2tex
sage: _ = tikz.pdf()      # not tested

Using merge_multiedges with merge_label_function:

sage: fn = lambda L: LatexExpr(','.join(map(str, L)))
sage: G = DiGraph([(0,1,'a'), (0,1,'b'), (0,2,'c'), (0,2,'d')], multiedges=True)
sage: tikz = TikzPicture.from_graph(G, merge_multiedges=True,
....:               merge_label_function=fn) # optional dot2tex
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()
sage: G
Looped multi-digraph on 27 vertices
sage: C = G.strongly_connected_components()
sage: tikz = TikzPicture.from_graph(G, merge_multiedges=False,
....:                               subgraph_clusters=C)
sage: _ = tikz.pdf()      # not tested
classmethod from_graph_with_pos(graph, scale=1, merge_multiedges=True, merge_label_function=<type 'tuple'>)

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

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 slabbe import TikzPicture
sage: g = graphs.PetersenGraph()
sage: tikz = TikzPicture.from_graph_with_pos(g)
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)
sage: G.set_pos({0:(0,0), 1:(1,0)})
sage: f = lambda label:','.join(label)
sage: TikzPicture.from_graph_with_pos(G, merge_label_function=f)
\documentclass[tikz]{standalone}
\standaloneconfig{border=4mm}
\usepackage{amsmath}
\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}

TESTS:

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)
sage: TikzPicture.from_graph_with_pos(G)
Traceback (most recent call last):
...
ValueError: vertex positions need to be set first
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.

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 slabbe import TikzPicture
sage: P = posets.PentagonPoset()
sage: tikz = TikzPicture.from_poset(P) # optional dot2tex # long time (3s)
sage: tikz = TikzPicture.from_poset(P, prog='neato', color_by_label=True) # optional dot2tex # long time (3s)
sage: P = posets.SymmetricGroupWeakOrderPoset(4)
sage: tikz = TikzPicture.from_poset(P) # optional dot2tex # long time (4s)
sage: tikz = TikzPicture.from_poset(P, prog='neato') # optional dot2tex # long time (4s)
tikz_picture_code()

EXAMPLES:

sage: from slabbe 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}