LaTeX/PGF/TikZ



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/

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 environment
Using TikZ in a LaTeX document requires the tikz package which can be loaded by adding following command in preamble of latex document: 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. For example A list of common libraries is following

Tikz environment
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.   One special option for this case is  . 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" environment

The entire figure can be scaled using the or different for height and width, e.g:

Specifying coordinates
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 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:

The coordinates can be associated with a name, e.g. A= (2,3), in many ways as stated following
 * 1) Without specifying a unit , the standard one is cm.
 * 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.


 * 1) When we know exact coordinates values for a point, then following command can be used.
 * 2) When a point is specified with respect to some other point one should use the path command.  . 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.

Syntax for paths
A path is a series of straight and curved line segments (in a simplified explanation). The instruction has to end with a semicolon. One instruction can spread over several lines, or several instructions can be put on one line.

Path actions
Options for path actions are e.g: " ", " ", " ", " ", " ", " ". These may be used as following Above command can also be written equivalently as " ", " ", " ", " ", " ", " ", " ", " ". These commands are explained in details in subsequent section

Geometric path actions
Geometric path options: " ", " ", " ", " ", " ", " ".

Color and opacity
The most common way is to specify just the color name or " ". 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

" ", " "

" ", " "

" ", " "

" ",

..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 width
Line width options: " ", and abbreviations " " for 0.1pt, " " for 0.2pt, " " for 0.4pt (the default width), " " for 0.6pt, " " for 0.8pt, " " for 1.2pt, " " for 1.6pt.

Line end
Line end, line join options: " ", " ", " ", " ", " ".

Line pattern
Line pattern options: " " (e.g. " "), " ", " ", " ", " ", " ", " ", " ", " ".

Options for filling paths are e.g. " ", " ", " "

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

Drawing straight lines

 * 1) Straight lines are given by coordinates separated by a double minus.
 * 2) A connected path can be closed using the " " option, which connects the last and first coordinate by a straight line.
 * 3) 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).
 * 4) 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 or first vertical then horizontal, use

Drawing curved paths

 * 1) Bezier curve can be drawn using the " " command, with one or two control points.
 * 2) User-defined paths can be created using the " " operation. Without an option it corresponds to a straight line, exactly like the double minus command. Using the " " and " " option a curved path can be created. E.g. " " 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. (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 :

 * 1) Rectangle
 * 2) Circle & Ellipses: The  command " "  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.
 * 3) Arcs: The command " " creates a part of a circle or an ellipse. Or in an alternative syntax:
 * 4) Helplines, Parabola,  Sine and Cosine curve: There are many more predefined commands for special paths, like " ", " ", " ", " " (sine or cosine curve in the interval [0,π/2]). The option "help lines" denotes "fine gray".

Changing line appearance using Options
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.

Examples for changing the arrow tips

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

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

= The \node command = 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

Different options are available, some of which are described in below table. A few examples are provided later for their better explanation. A few examples are given below to explain the options
 * 1) Using the \node command. The syntax of the command is     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.
 * 2) Using the keyword node with other command viz. \draw and \path command.

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

To place nodes on a line or a curve use the " " option, where fraction is a floating point number between 0 representing the previous coordinate and 1 representing the current coordinate. There exist some abbreviations: " " for " ", " " for " ", " " for " ", " " for " ", " " for " ", " " for " ", " " for " ".

The " " 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: One can connect nodes using the nodes' labels as coordinates. Having " " defined, the node at (0,0) got the name " " and the one at (3,1) got the name " ". Equivalent to 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:

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. Once the node x has been defined, you can use anchors as defined above relative to (x) as " ", like " ".

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 makes use of "foreach command" whose details can be found in the special command section.

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

= Special commands =

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

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

Foreach command
This command is analogous to loops used in programming. It can be realized by " ".

Animation in Beamer style
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 There are three important steps, as described below.


 * 1) Define a new variableː In above example we used   as the variable which store the count.
 * 2) Define the range the variable can take. We use the command     which says- For the range of 0-100, create 10 values.  The <1-10> means the new variable has following set of values   The <3-10> means the new variable has following set of values
 * 3) Use the variable for object position, which is done using

PGF layers
There are two ways to place the curves in the background--


 * 1) First way is to write the command in the sequential order, i.e. first draw the curves at background (for which coordinates are already available), then draw the curves which comes on top of that, and so on.
 * 2) Second way is to use PGF layers. This is particularly useful, when the background curves coordinates are not already available. They are defined with respect to the upper layer curves.

PGF layers provides following commands

Pattern Library
This library can provide total 11 types of patterns which can be used to fill the given area. Its color can be chose with the help of keyword. These patterns are listed as below:

Snake library
This library changes the path structure from a straight line to the following. Some parameters that influence the nature of curve are

segment amplitude=.4mm,

segment length=2mm,

segment object length=.5mm

segment angle = 20

segment aspect=0

raise snake = .2mm

mirror snake

line before snake=1mm, line after snake=1mm, line around snake=1mm,

gap before snakes=1mm, gap after snakes=1mm, gap around snake=1mm

Calc Package
The calc package can be included using the command. This package can be used to perform simple calculations with coordinates.


 * Coordinate algebra.
 * Finding midpoints A special function   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)

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

PGF Maths
A number of mathematical operation can be performed using the  which provides a core command   and return the result in. A few example are In above example we have used the function. A substitute for above command is.

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:   :   Finds the angle of the line passing through the points P to Q.     :  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.

= PGF Plots = PGF also has a math engine which enables you to plot functions: 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  and   in the expression.

An example with two functions:

= Examples =