LaTeX/PGF/TikZ

LaTeX logo.svg

LaTeX

Getting Started
  1. Introduction
  2. Installation
  3. Installing Extra Packages
  4. Basics
  5. How to get help

Common Elements

  1. Document Structure
  2. Text Formatting
  3. Paragraph Formatting
  4. Colors
  5. Fonts
  6. List Structures
  7. Special Characters
  8. Internationalization
  9. Rotations
  10. Tables
  11. Title creation
  12. Page Layout
  13. Customizing Page Headers and Footers‎
  14. Importing Graphics
  15. Floats, Figures and Captions
  16. Footnotes and Margin Notes
  17. Hyperlinks
  18. Labels and Cross-referencing
  19. Initials

Mechanics

  1. Errors and Warnings
  2. Lengths
  3. Counters
  4. Boxes
  5. Rules and Struts

Technical Text

  1. Mathematics
  2. Advanced Mathematics
  3. Theorems
  4. Chemical Graphics
  5. Algorithms
  6. Source Code Listings
  7. Linguistics

Special Pages

  1. Indexing
  2. Glossary
  3. Bibliography Management
  4. More Bibliographies

Special Documents

  1. Scientific Reports (Bachelor Report, Master Thesis, Dissertation)
  2. Letters
  3. Presentations
  4. Teacher's Corner
  5. Curriculum Vitae
  6. Academic Journals (MLA, APA, etc.)

Creating Graphics

  1. Introducing Procedural Graphics
  2. MetaPost
  3. Picture
  4. PGF/TikZ
  5. PSTricks
  6. Xy-pic
  7. Creating 3D graphics

Programming

  1. Macros
  2. Plain TeX
  3. Creating Packages
  4. Creating Package Documentation
  5. Themes

Miscellaneous

  1. Modular Documents
  2. Collaborative Writing of LaTeX Documents
  3. Export To Other Formats

Help and Recommendations

  1. FAQ
  2. Tips and Tricks

Appendices

  1. Authors
  2. Links
  3. Package Reference
  4. Sample LaTeX documents
  5. Index
  6. Command Glossary

edit this boxedit the TOC

One way to draw graphics directly with TeX commands is PGF/TikZ. TikZ can produce portable graphics in both PDF and PostScript formats using either plain (pdf)TEX, (pdf)Latex or ConTEXt. It comes with very good documentation and an extensive collection of examples: http://www.texample.net/tikz/

Example of graphics done with Tikz. Note the slightly translucent top layer.

PGF ("portable graphics format") is the basic layer, providing a set of basic commands for producing graphics, and TikZ ("TikZ ist kein Zeichenprogramm" or "TikZ is not a Drawing program") is the frontend layer with a special syntax, making the use of PGF easier. TikZ commands are prevalently similar to Metafont, the option mechanism is similar to PsTricks syntax.

While the previous systems (picture, epic, pstricks or metapost) focus on the how to draw, TikZ focuses more on the what to draw. One could say that TikZ is to picture as LaTeX is to TeX. It's recommended to use it if your LaTeX distribution includes it.

Other packages building on top of TikZ (e.g., for drawing electrical circuits) can be found here: https://www.ctan.org/topic/pgf-tikz

In the following some basics of TikZ are presented.

Loading package, libraries - tikzpicture environmentEdit

Using TikZ in a LaTeX document requires the tikz package which can be loaded by adding following command in preamble of latex document:

\usepackage{tikz}                    % in preamble

This will provide basic functionalities, and also load the pgf package automatically. For special features special libraries must be included. It requires following in the preamble part of the code.

\usetikzlibrary{⟨list of libraries separated by commas⟩}   % general syntax, in preamble

For example

\usetikzlibrary{arrow,pattern, snakes}               % in preamble

A list of common libraries is following

Library Name Description
\usetikzlibrary{arrows.meta} Arrow library that provides different types of arrow tips (Note: \usetikzlibrary{arrows} is deprecated).
\usetikzlibrary{automata} Automata Drawing Library that is used for drawing the finite state automata and Turing Machines.
\usetikzlibrary{backgrounds} Background Library that "defines background for pictures".
\usetikzlibrary{calc} Library to make complex coordinate calculations.
\usetikzlibrary{calendar} This library is used to display calendars (I guess it's a Ronseal thing).
\usetikzlibrary{chains} Chain library to align nodes o chains.
Decorations libraries to decorate paths
\usetikzlibrary{er} Entity Relationship Diagram Library.
\usetikzlibrary{intersections} to calculate intersections of paths.
\usetikzlibrary{matrix} Matrix Library that places each item as a node in same way as in a matrix. Each node can then be identified and manipulated.
\usetikzlibrary{folding} Paper folding library.
\usetikzlibrary{patterns} It provides different patterns for filling in area (horizontal lines, vertical lines, north east lines, north west lines, grid, crosshatch, dots, crosshatch dots, fivepointed stars, sixpointed stars).
\usetikzlibrary{petrinet} It is used to draw Petri Nets, as used for mathematical modelling. As with other similar flowchart style diagrams, each node and edge is defined, as well as their style and position. Tokens can also be embedded within nodes, by treating them as children and child nodes.
\usetikzlibrary{shapes.geometric} It can help in drawing different types of shapes e.g., a polygon of n sides, star shape with n points, forbidden sign (e.g. No Smoking sign), and split circle.
\usetikzlibrary{shapes.misc}
\usetikzlibrary{shadows}
\usetikzlibrary{snakes} It helps in drawing curves like- snake, spring, expanding wave, etc.
\usetikzlibrary{spy}
\usetikzlibrary{trees} Each point on the tree is defined as a node, with children, and each child can have its own children. The tree's direction can also be specified, as well as the angle at which children emerge, however, when left to its own devices, the results are acceptable.
\usetikzlibrary{mindmap} Mind map library to show parent-child type relation in a more creative way.


Tikz environmentEdit

The figures are drawn in the main body part the Tex document. There are two ways to use it

  1. Inline Mode: Which should be used when you want to draw inline with text.
    \tikz[⟨options⟩]{⟨tikz commands⟩}
    
    One special option for this case is baseline = <dimension>. Without that option the lower end of the picture is put on the baseline of the surrounding text. Using this option, you can specify that the picture should be raised or lowered such that the height ⟨dimension⟩ is on the baseline.
  2. Tikzpicture environement: The drawing commands have to be enclosed in an "tikzpicture" environmen
    \begin{tikzpicture}[⟨options⟩] 
      ⟨tikz commands⟩
    \end{tikzpicture}
    

The entire figure can be scaled using the

scale=⟨factor⟩

or different for height and width, e.g:

xscale=2.5, yscale=0.5

Specifying coordinatesEdit

Coordinates are specified in round brackets in an arbitrary TEX dimension either using Cartesian coordinates (comma separated), e.g. 1cm in the x direction and 2pt in the y direction

Coordinate type Syntax Example
Cartesian (x,y) (1cm,2pt)
Polar (theta:radius) (30:1cm)
Relative to last position ++(x,y) ++(2cm,2cm)

In the first row of table the Cartesian coordinates (comma separated) are shown. In the second row the polar coordinates (colon separated), e.g. 1cm in 30 degree direction

Relative coordinates to the previous given point are given by adding one or two plus signs in front of the coordinate. With "++" the last point of the path becomes the current position, with "+" the previous point stays the current path position. Example: 2 standard units to the right of the last point used:

Note:

  1. Without specifying a unit (1,2), the standard one is cm (1cm,2cm).
  2. The positive x and y directions refer to right and up on a diagram respectively.
  3. The angle are measured from x axis and positive for a counter-clockwise direction. This means 0 degrees pointing directly right and 90 degree point up.

The coordinates can be associated with a name, e.g. A= (2,3), in many ways as stated following

  1. When we know exact coordinates values for a point, then following command can be used. \coordinate (A) at (2,3);
  2. When a point is specified with respect to some other point one should use the path command. \path (A)  ++(45:2) coordinate (B);. The command says- start from coordinate A, move along 45 degree direction for 2cm, and this final location coordinate should be assigned to B.
  3. To define the coordinates and place a text as well use the node command. \node (A) at (90:0) {Coordinate Name}

Syntax for pathsEdit

A path is a series of straight and curved line segments (in a simplified explanation). The instruction has to end with a semicolon.

\path[<options>]⟨specification⟩;

One instruction can spread over several lines, or several instructions can be put on one line.

Path actionsEdit

Options for path actions are e.g: "draw", "fill", "pattern", "shade", "clip" , "use as bounding box". These may be used as following

\path[draw]             % Draw the line/curve 
\path[fill]             % Fill the area under the curve
\path[fill,draw]        % Fill as well as draw the lines (boarders)
\path[pattern]          % 
\path[shade]            % a variation on filling that changes colors smoothly from one to another
\path[shade,draw]       % shade as well a draw 
\path[clip]             % all subsequent drawings up to the end of the current scope are clipped against the current path and the size of subsequent paths will not be important for the picture size 
\path[use as bounding box]

Above command can also be written equivalently as "\draw", "\fill", "\filldraw", "\pattern", "\shade", "\shadedraw", "\clip", "\useasboundingbox" . These commands are explained in details in subsequent section

Geometric path actionsEdit

Geometric path options: "rotate=<angle in degree>", "xshift=<length>", "yshift=<length>", "scale=<factor>", "xscale=<factor>", "yscale=<factor>".

Color and opacityEdit

The most common way is to specify just the color name or "color=<color name>". In this case it will color the boarders/area according to the command (\draw,\fill) used.

There can be different elements in a drawing so it may require specifying them separately for which one may use

"draw=<line color>", "draw opacity=<factor>"

"fill=<fill color>", "fill opacity = <factor>"

"text=<text color>", "text opacity=<factor>"

"pattern color=<color>",

..etc

Predefined colors: red, green, blue, cyan, magenta, yellow, black, gray, darkgray, lightgray, brown, lime, olive, orange, pink, purple, teal, violet and white.

The opacity factor values can be in range of 0 (=fully transparent) to 1 (=fully opaque).

Line widthEdit

Line width options: "line width=<dimension>", and abbreviations "ultra thin" for 0.1pt, "very thin" for 0.2pt, "thin" for 0.4pt (the default width), "semithick" for 0.6pt, "thick" for 0.8pt, "very thick" for 1.2pt, "ultra thick" for 1.6pt.

Line endEdit

Line end, line join options: "line cap=<type: round, rect, or butt>", "arrows=<start arrow kind>-<end arrow kind>", "rounded corners", "rounded corners=<size>", "line join=<type: round, bevel, or miter>".

Line patternEdit

Line pattern options: "dash pattern=<dash pattern>" (e.g. "dash pattern=on 2pt off 3pt on 4pt off 4pt"), "dash phase=⟨dash phase⟩", "solid", "dashed", "dotted", "dashdotted", "densely dotted", "loosely dotted", "double".


Options for filling paths are e.g. "fill=<fill color>", "pattern=<name>", "pattern color=<color>"

The \draw commandEdit

The draw command can be used in several ways with different options. A few examples are provided as follows.

Drawing straight linesEdit

  1. Straight lines are given by coordinates separated by a double minus .
\draw (1,0) -- (0,0) -- (0,1);

 

  1. A connected path can be closed using the "--cycle" option, which connects the last and first coordinate by a straight line.
\draw (1,0) -- (0,0) -- (0,1) -- cycle;

 

  1. A further move-to operation in an existing path starts a new part of the path, which is not connected to the previous part of the path. Here: Move to (0,0) straight line to (2,0), move to (0,1) straight line to (2,1).
\draw (0,0) -- (2,0) (0,1) -- (2,1);

 

  1. Two points can be connected by straight lines that are only horizontal and vertical. For a connection that is first horizontal and then vertical, use
\draw (0,0) -| (1,1);

 

or first vertical then horizontal, use

\draw (0,0) |- (1,1);

 

Drawing curved pathsEdit

  1. Bezier curve can be drawn using the "..controls() ..()" command, with one or two control points.
\draw (0,0) .. controls (1,1) .. (4,0)
      (5,0) .. controls (6,0) and (6,1) .. (5,2);

 

  1. User-defined paths can be created using the "to" operation. Without an option it corresponds to a straight line, exactly like the double minus command. Using the "out" and "in" option a curved path can be created. E.g. "[out=135,in=45]" causes the path to leave at an angle of 135 degree at the first coordinate and arrive at an angle of 45 degree at the second coordinate.
\draw (0,0) to (3,2);
\draw (0,0) to[out=90,in=180] (3,2);
\draw (0,0) to[bend right] (3,2);

 

(The syntax for a bend to the right may seem a little counter-intuitive. Think of it as an instruction to veer to the right at the beginning of the path and then smoothly curve to the end point, not as saying that the path curves to the right throughout its length.)

Draw special curves :Edit

  1. Rectangle
    \draw (0,0) rectangle (2,3);
    
  2. Circle & Ellipses: The command "circle" can be used to draw both circle and ellipses. For circle only radius is required, while for ellipse length of major axis and minor axis is required.
\draw (0,0) circle [radius=1.5];
\draw (0,0) circle (2cm); % old syntax with round brackets instead of square brackets
\draw (0,0) circle [x radius=1.5cm, y radius=10mm];
\draw (0,0) circle (1.2cm and 8mm); % old syntax
\draw (0,0) circle [x radius=1cm, y radius=5mm, rotate=30];
\draw[rotate=30] (0,0) ellipse (20pt and 10pt);  % old syntax

 

  1. Arcs: The command "arc" creates a part of a circle or an ellipse.
\draw (0,0) arc (0:270:8mm);
\draw (0,0) arc (0:315:1.75cm and 1cm);
\filldraw[fill=cyan, draw=blue] (0,0) -- (12mm,0mm) arc (0:30:12mm) -- (0,0);

 

Or in an alternative syntax:

\draw (0,0)  arc[radius = 8mm, start angle= 0, end angle= 270];
\draw (0,0)  arc[x radius = 1.75cm, y radius = 1cm, start angle= 0, end angle= 315];
  1. Helplines, Parabola, Sine and Cosine curve: There are many more predefined commands for special paths, like "grid", "parabola", "sin", "cos" (sine or cosine curve in the interval [0,π/2]). The option "help lines" denotes "fine gray".
\draw[help lines] (0,0) grid (2,3);
\draw[step=0.5, gray, very thin] (-1.4,-1.4) grid (1.4,1.4);
\draw (0,0) parabola (1,1.5) parabola[bend at end] (2,0);
\draw (0,0) sin (1,1) cos (2,0) sin (3,-1) cos (4,0) sin (5,1);

 

Changing line appearance using OptionsEdit

The line has many attributes which can be altered according requirement. For example in following example we chose the line color as red, line pattern as dashed, and the line width as very thick.

\draw[red, dashed, very thick, rotate=30] (1,0) -- (0,0) -- (0,1);

 

Examples for changing the arrow tips

\draw [->] (0,0) -- (30:20pt); 
\draw [<->] (1,0) arc (180:30:10pt); 
\draw [<<->] (2,0) -- ++(0.5,10pt) -- ++(0.5,-10pt) -- ++(0.5,10pt);

 

List of options for changing the line appearance.
Description Option passed Acceptable Value Remark
Changing width of line line width=1mm any The values can be provided in pt, mm, cm, in, etc
line width= thick ultra thin,

very thin, thin semi thick thick very thick ultra thick

These values are corresponding to (0.1pt, 0.2pt, 0.4pt, 0.6pt, 0.8pt, 1.2pt, 1.6pt)
Changing the line end shape line cap = round round, rect, butt
Changing the line pattern solid solid, dashed, dotted, dash dotted, densely dotted, loosely dotted, double, Predefined line patterns
dash pattern=on 2pt off 3pt on 4pt off 4pt Customized line pattern
Arrow type arrow= <-> >,<, >>, >>, latex, stealth,
Joining lines line join= miter round, bevel, miter
Example: \draw[very thick, line cap=round, arrow=latex-latex, line join=round] (0,0)--(3,2);

For rectangles a special syntax exists. Use a move-to operation to one corner and after "rectangle" the coordinates of the diagonal corner. The last one becomes the new current point.

\draw (0,0) rectangle (1,1);
\shade[top color=yellow, bottom color=black] (0,0) rectangle (2,-1);
\filldraw[fill=green!20!white, draw=green!40!black] (0,0) rectangle (2,1);

 

The fill color "green!20!white" means 20% green and 80% white mixed together.

The \node commandEdit

A node is used to place some text at given coordinate. Nodes are not part of the path itself, they are added to the picture after the path has been drawn.

The node can be placed inside rectangle or circle or other simple shapes. A node can be placed in several ways

  1. Using the \node command. The syntax of the command is \node[options] (Name) at (coordinates) {Text};
    %% syntax
    %% \node[options] (Name of node) at (coordinates) {Text to appear};
    % Example for usage
    \node[red,rectangle] at (0,0) {Some text}; % To place some text only
    \node (A) at (0,0) {}; % To define a new coordinate
    
    The name of node should be given in parenthesis. An example is given following, where two nodes are drawn and first is within the circle and second is in the rectangle.
    \begin{tikzpicture}
    	\node (A) at (0,0) [thick,blue, circle,fill=blue!50] {Encoder};   % node A
    	\node (B) at (3,0) [thick,blue,rectangle,fill=green!80!black] {Decoder}; % node B
    	\draw[->,ultra thick] (A)--(B); % line joining node A and B
    \end{tikzpicture}
    
  2. Using the keyword node with other command viz. \draw and \path command.
    \draw (0,0) node{a} -- (1,1) node {b};
    \path (0,0) node{a} -- (1,1) node {b};
    

Different options are available, some of which are described in below table. A few examples are provided later for their better explanation.

Description Option passed Admissible values Remark
Position of text along a path pos=.5 > 0 The text will be place along path at beginning (=0), in middle (=.5) and at end(=1). (default=1)
Alignment of text align=left left, right, center The text/paragraph is aligned accordingly (default=center).
Place the text wrt a given point anchor=top left, right, top, bottom, top left, top right, bottom left, bottom right. Assuming the point as origin there are 4 directions (x,-x, y, -y) for which left,right,top,bottom corresponds. 4 quadrants (I,II,III,IV).
anchor=north east,west, north, south, north east, north west, south east, south west Same as above but now direction are specified with north, east, west, south.
Text enclose in shape rectangle, circle, Associated parameter should be passed along with option.
Distance between the enclosed shape and the text Inner sep =.5
Distance of the enclosing shape from the point Outer sep =.8
Minimum size of the shape irrespective of the text length. minimum width = 2cm any value>0 The width of the shape (lets assume a rectangle) will be at least 2cm even for a single letter. However, size may increase for very lengthy text.

Note: The size of node = max(minimum width, inner sep). To achieve smaller size, you must reduce both.

minimum height = 2cm any value>0 Minimum height of the node containing shape
minimum size = 2cm any value>0 Minimum height as well as width of the shape.
The aspect ratio of the shape to be maintained shape aspect = 1 The shape enclosing text will change its dimension maintaining this aspect ratio.
coloring text, color shape, etc. fill= red, draw=green This is usual as described in earlier color and opacity options.
Aligning the text along the curve sloped

A few examples are given below to explain the options


Writing text along a given path using the node command is shown as a simple example:

\draw[dotted]
    (0,0) node {1st node}
 -- (1,1) node {2nd node}
 -- (0,2) node {3rd node}
 -- cycle;

 

\fill[fill=yellow]
    (0,0) node {1st node}
 -- (1,1) node[circle,inner sep=0pt,draw] {2nd node}
 -- (0,2) node[fill=red!20,draw,double,rounded corners] {3rd node};

 

To place nodes on a line or a curve use the "pos=<fraction>" option, where fraction is a floating point number between 0 representing the previous coordinate and 1 representing the current coordinate.

\draw (0,0) -- (3,1)
  node[pos=0]{0} node[pos=0.5]{1/2} node[pos=0.9]{9/10};

 

There exist some abbreviations: "at start" for "pos=0", "very near start" for "pos=0.125", "near start" for "pos=0.25", "midway" for "pos=0.5", "near end" for "pos=0.75", "very near end" for "pos=0.875", "at end" for "pos=1".

The "sloped" option causes the node to be rotated to become a tangent to the curve.

Since nodes are often the only path operation on paths, there are special commands for creating

paths containing only a node, the first with text ouput, the second without:

\node[<options>](<name>) at (<coordinate>){<text>};
\coordinate[<options>](<name>) at (<coordinate>);

One can connect nodes using the nodes' labels as coordinates. Having "\path(0,0) node(x) {} (3,1) node(y) {};" defined, the node at (0,0) got the name "(x)" and the one at (3,1) got the name "(y)".

\path (0,0) node(x) {} 
      (3,1) node(y) {};
\draw (x) -- (y);

 

Equivalent to

\coordinate (x) at (0,0); 
\coordinate (y) at (3,1);
\draw (x) -- (y);

Multiline text can be included inside a node. A new line is indicated by double backslash "\\", but additionally you have to specify the alignment using the node option "align=". Here an example:

\filldraw 
(0,0) circle (2pt) node[align=left,   below] {test 1\\is aligned left} --
(4,0) circle (2pt) node[align=center, below] {test 2\\is centered}     -- 
(8,0) circle (2pt) node[align=right,  below] {test 3\\is right aligned};

 


Path construction operations try to be clever, such that the path starts at the border of the node's shape and not from the node's center.

\path (0,0) node(x) {Hello World!}
(3,1) node[circle,draw](y) {$\int_1^2 x \mathrm d x$};
\draw[->,blue] (x) -- (y);
\draw[->,red] (x) -| node[near start,below] {label} (y);
\draw[->,orange] (x) .. controls +(up:1cm) and +(left:1cm) .. node[above,sloped] {label} (y);

 

Once the node x has been defined, you can use anchors as defined above relative to (x) as "(x.<anchor>)", like "(x.north)".


Placing circles along the drawn curve:

In this case a curve is drawn and over that curve some circles are placed at specified positions. This trick make use of "foreach command" whose details can be found in the special command section.

\draw[very thick] (0.5,0.5) .. controls (2,1).. (2.5,2.5)
	node foreach \p in {0,0.25,...,1} [circle,fill=red,pos=\p,inner sep=0pt,minimum size=1.5mm]{};	
\node[left] at (.5,.30){A};
\node[right] at (2.5,2.5){B} ;	
\path[ultra thick,latex-latex] (2,0) --(0,0)--(0,1.5);

The \clip commandEdit

The clip command is used to remove the portion outside the given shape (e.g. rectangle or circle).

\begin{tikzpicture}
	\clip (1,1)  circle (2);
	\draw[red,fill] (0,0) rectangle (3,3);		
\end{tikzpicture}

Special commandsEdit

TikzstyleEdit

It is a very useful command when you need to set several different shapes with same parameters (i.e., width, color, etc). Therefore you can define one or more style in the beginning, as shown below and then you may use it later anywhere in the Tikz code.

\begin{tikzpicture}[
mycircle/.style={circle, draw=green!60, fill=green!5, ultra thick, minimum size=7mm},
myline/.style={dotted, blue!60,->},
]
\draw[myline] (0,0)node[mycircle]{$\pi$} to[out=45,in=135]  (5,1) node[mycircle]{3.414...};
\end{tikzpicture}

ScopeEdit

You may want to apply some changes to only a certain part of the code then it can be done use the scope command.

\begin{tikzpicture}[
mycircle/.style={circle, draw=green!60, fill=green!5, ultra thick, minimum size=7mm},
myline/.style={dotted, blue!60,->},
]
\draw[myline] (0,0)node[mycircle]{$\pi$} to[out=45,in=135]  (5,1) node[mycircle]{3.414...};
% following drawing in the scope is shifted along y by 2cm
\begin{scope}[yshift=2cm]
	\draw[myline] (0,0)node[mycircle]{$\pi$} to[out=45,in=135]  (5,1) node[mycircle]{3.414...};
\end{scope}
\end{tikzpicture}

Foreach commandEdit

This command is analogous to loops used in programming. It can be realized by "\foreach ⟨variable⟩ in {⟨list of values⟩} ⟨commands⟩".

\foreach \x in {0,...,9} 
  \draw (\x,0) circle (0.4);

 

Animation in Beamer styleEdit

To achieve the animation in the beamer in simplest form, we can print the N number of frames with the object being shifted in N-steps. An example is given following

\begin{frame}
\newcount\p
\animatevalue<3-10>{\p}{0}{100}
\begin{tikzpicture}
	\path(0,0)rectangle(0.75\paperwidth,-0.75\paperheight);
	\path[draw](0,0)..controls +(30:2) and +(40:2)..+(4,-1) node [pos=\p/100,sloped,above]{a};

\end{tikzpicture}
\end{frame}

There are three important steps, as described below.

  1. Define a new variableː In above example we used \p as the variable which store the count.
  2. Define the range the variable can take. We use the command \animatevalue<3-10>{\p}{0}{100} which says- For the range of 0-100, create 10 values. The <1-10> means the new variable has following set of values \p =[1,2,3,...,10] The <3-10> means the new variable has following set of values \p =[0,0,0,1.25,2.5,...,10].
  3. Use the variable for object position, which is done using \path[draw](0,0)..controls +(30:2) and +(40:2)..+(4,-1) node [pos=\p/100,sloped,above]{a};

Calc PackageEdit

The calc package can be included using the command \usetikzlibrary{calc}. This package can be used to perform simple calculations with coordinates.

  • Coordinate algebra.
    \coordinate (A) at (2,3);
    \coordinate (B) at (1.5,2.5);
    \coordinate (B) at ($(A) + (B)$)
    \coordinate (B) at ($(A) - (B)$)
    \coordinate (B) at ($(A) + 2*(A)$)
    
  • Finding midpoints
    \coordinate (A) at (0,0);
    \coordinate (B) at (90:3);
    \coordinate (B) at (0:4);
    \coordinate (Ap) at ($(B)!0.5!(C)$);
    \coordinate (Bp) at ($(A)!0.5!(C)$);
    \coordinate (Cp) at ($(A)!0.5!(B)$);
    \draw (A)--(B)--(C)--cycle
          (A)--(Ap) 
          (B)--(Bp) 
          (C)--(Cp);
    
    A special function veclen is provided by the package which can be used to calculate the distance between the points as follows (taken from sec. 1.15 in https://tikz.dev/tikz-paths)
    \usetikzlibrary {calc}
    \begin{tikzpicture}
      \draw [help lines] (0,0) grid (3,3);
      \coordinate (a) at (rnd,rnd);
      \coordinate (b) at (3-rnd,3-rnd);
      \draw (a) -- (b);
      \node (c) at (1,2) {x};
      \draw let \p1 = ($ (a)!(c)!(b) - (c) $),
                \n1 = {veclen(\x1,\y1)}
            in circle [at=(c), radius=\n1];
    \end{tikzpicture}
    

Intersection libraryEdit

This library is used to find the intersection of any two curves. and example is given below

\usepackage{tikz}
\usetikzlibrary{intersections}

\begin{document}
\begin{tikzpicture}
\draw[name path=line,smooth] (0,5)--(1.5,5);
\draw[name path=curve,smooth] (1.5,6) to[out=270,in=90] (0,3);
\draw[name intersections={of=line and curve}] (intersection-1) circle[radius=0.1];
\end{tikzpicture}
\end{document}

Applying intersection with many curves

\begin{tikzpicture}
\draw[name path=grid] [xstep=3,ystep=2] (0,0) grid (9,8);
\draw[->, name path=line] (2,1) -- (7,7);
\draw[name intersections={of=grid and line, sort by=line, name=i, total=\t}]
\foreach \s in {1,...,\t}{(i-\s) node {\s}};
\end{tikzpicture}

PGF MathsEdit

A number of mathematical operation can be performed using the \usepackage[pgfmath] which provides a core command \pgfmathparse and return the result in \pgfmathresult. A few example are

\pgfmathparse{add(75,6)} \pgfmathresult

In above example we have used the function add(x,y). A substitute for above command is \pgfmathadd{x}{y}.

A number of function available, which are provided as following. The substitute command can be obtained as for the add function, i.e. by using a prefix \pgfmath with command name.

  • add(a,b), subtract (a,b), multiply(a,b), divide(a,b), div(a,b), neg (-a), sqrt(a), pow (a^b), exp(a), ln(a), log10(a), log2(a), abs(a), mod(a,b)
  • round(a), floor(a), ceil(a), int(a), frac(a)
  • check for type: isodd(a), iseven(a), isprime(a)
  • Constants: e, pi
  • conversion: rad(x), deg(y)
  • Trigonometric functions: sin(x), cos(x), tan(x), sec(x), cosec(x) , cot(x),
  • Inverse trigonometric functions: asin(x), acos(x), atan(x)
  • Comparison: equal(x,y), greater(x,y), less(x,y), notequal(x,y), notgreater(x,y), notless(x,y),
  • Logical functions: and(x,y), or(x,y), not(x), ifthenelse(x,y,z), and logical constants as-- true, false.
  • Random no generator: rnd, rand, random(x,y)
  • Miscelleneous: Minimum/Maximum from an list of elements : min(x1,x2,...,xn), max(x1,x2,...,xn), Length of a vector: veclen(x,y) Access i th element of an given array x: array({x1,x2,x3,...,xn},i)
  • Computing angles: \pgfmathanglebetweenpoints{P}{Q} : Finds the angle of the line passing through the points P to Q. \pgfmathanglebetweenlines{P1}{Q1}{P2}{Q2} : Finds the angle between the two lines, L1 and L2, where L1 passing through P1 and Q1, and second line passing through P2 and Q2.
Commands Description
\pgfmathsetlength{name}{value} \pgfmathaddtolength{name}{value} Set the corresponding "name" tex register for given value
\pgfmathsetcount{name}{value} \pgfmathaddtocount{name}{value}
\pgfmathsetcounter{name}{value} \pgfmathaddtocounter{name}{value}
\pgfmathsetmacro{name}{value} \pgfmathtruncatemacro{name}{value}


PGF PlotsEdit

PGF also has a math engine which enables you to plot functions:

\draw [domain=xmin:xmax] plot (\x, {function});

Many functions are possible, including factorial(\x), sqrt(\x), pow(\x,y), exp(\x), ln(\x), log10(\x), log2(\x), abs(\x), mod(\x,y), round(\x), floor(\x), ceil(\x), sin(\x), cos(\x), tan(\x), min(\x,y,), and max(\x,y).

Noteː

1) The trigonometric functions assume that x is in degrees; to express x in radians follow it with the notation "r", e.g., sin(\x r).

2) Two useful constants are e =2.718281828, and pi = 3.141592654 can be specified directly using e and pi in the expression.

An example with two functions:

\draw [help lines] (-2,0) grid (2,4); 
\draw [->] (-2.2,0) -- (2.2,0); 
\draw [->] (0,0) -- (0,4.2); 
\draw [green, thick, domain=-2:2] plot (\x, {4-\x*\x}); 
\draw [domain=-2:2, samples=50] plot (\x, {1+cos(pi*\x r)});

 

ExamplesEdit

Example 1Edit

\documentclass{article}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture}
  \draw[thick,rounded corners=8pt] (0,0) -- (0,2) -- (1,3.25) 
   -- (2,2) -- (2,0) -- (0,2) -- (2,2) -- (0,0) -- (2,0);
  \end{tikzpicture}
\end{document}

 

Example 2Edit

\documentclass{article}
\usepackage{tikz}
\begin{document}
 \begin{tikzpicture}[scale=3]
 \draw[step=.5cm, gray, very thin] (-1.2,-1.2) grid (1.2,1.2); 
 \filldraw[fill=green!20,draw=green!50!black] (0,0) -- (3mm,0mm) arc (0:30:3mm) -- cycle; 
 \draw[->] (-1.25,0) -- (1.25,0) coordinate (x axis);
 \draw[->] (0,-1.25) -- (0,1.25) coordinate (y axis);
 \draw (0,0) circle (1cm);
 \draw[very thick,red] (30:1cm) -- node[left,fill=white] {$\sin \alpha$} (30:1cm |- x axis);
 \draw[very thick,blue] (30:1cm |- x axis) -- node[below=2pt,fill=white] {$\cos \alpha$} (0,0);
 \draw (0,0) -- (30:1cm);
 \foreach \x/\xtext in {-1, -0.5/-\frac{1}{2}, 1} 
   \draw (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north,fill=white] {$\xtext$};
 \foreach \y/\ytext in {-1, -0.5/-\frac{1}{2}, 0.5/\frac{1}{2}, 1} 
   \draw (1pt,\y cm) -- (-1pt,\y cm) node[anchor=east,fill=white] {$\ytext$};
 \end{tikzpicture}
\end{document}

 

Example 3: A TorusEdit

\documentclass{article}
\usepackage{tikz}
\begin{document}
 \begin{tikzpicture}
  \draw (-1,0) to[bend left] (1,0);
  \draw (-1.2,.1) to[bend right] (1.2,.1);
  \draw[rotate=0] (0,0) ellipse (100pt and 50pt);
\end{tikzpicture}
\end{document}

 

Example 4: Some functionsEdit

\documentclass{article}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture}[domain=0:4] 
    \draw[very thin,color=gray] (-0.1,-1.1) grid (3.9,3.9);
    \draw[->] (-0.2,0) -- (4.2,0) node[right] {$x$}; 
    \draw[->] (0,-1.2) -- (0,4.2) node[above] {$f(x)$};
    \draw[color=red]    plot (\x,\x)             node[right] {$f(x) =x$}; 
    \draw[color=blue]   plot (\x,{sin(\x r)})    node[right] {$f(x) = \sin x$}; 
    \draw[color=orange] plot (\x,{0.05*exp(\x)}) node[right] {$f(x) = \frac{1}{20} \mathrm e^x$};
  \end{tikzpicture}
\end{document}

 

RefrencesEdit

https://tikz.dev/http://tug.ctan.org/info/visualtikz/VisualTikZ.pdf

Previous: Picture Index Next: PSTricks