Draw Rectangle Onto the Tree 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 [edit | edit source]
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 environment [edit | edit source]
The figures are drawn in the main body part the Tex document. There are two ways to use it
- Inline Mode: Which should be used when you want to draw inline with text.
\tikz[⟨options⟩]{⟨tikz commands⟩}
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. - 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
or different for height and width, e.g:
Specifying coordinates [edit | edit source]
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:
- Without specifying a unit
(1,2)
, the standard one is cm(1cm,2cm)
. - The positive x and y directions refer to right and up on a diagram respectively.
- 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.
Syntax for paths [edit | edit source]
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 actions [edit | edit source]
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 actions [edit | edit source]
Geometric path options: "rotate=<angle in degree>
", "xshift=<length>
", "yshift=<length>
", "scale=<factor>
", "xscale=<factor>
", "yscale=<factor>
".
Color and opacity [edit | edit source]
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 width [edit | edit source]
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 end [edit | edit source]
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 pattern [edit | edit source]
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 command [edit | edit source]
The draw command can be used in several ways with different options. A few examples are provided as follows.
Drawing straight lines [edit | edit source]
- Straight lines are given by coordinates separated by a double minus .
\draw (1,0) -- (0,0) -- (0,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; |
|
- 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); |
|
- 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 [edit | edit source]
- 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); |
|
- 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 | edit source]
- Rectangle
\draw (0,0) rectangle (2,3);
- 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 |
|
- 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];
- 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 Options [edit | edit source]
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); |
|
Line width | Line end | Line pattern | |
---|---|---|---|
line width=<dimension> e.g. line width = 1mm | line cap=<type: round, rect, or butt> | dash pattern=<dash pattern> e.g. dash pattern=on 2pt off 3pt on 4pt off 4pt | |
ultra thin (equal to 0.1pt) | solid | ||
very thin (equal to 0.2pt) | arrows=<start arrow type> - <end arrow type> Arrow types: >, <,>>,<<, latex, stealth. e.g. | dashed | |
thin (default,equal to 0.4pt) | dotted | ||
semithick (equal to 0.6pt) | rounded corners=<size> | dashdotted | |
thick (equal to 0.8pt) | densely dotted | ||
very thick (equal to 1.2pt) | line join=<type: round, bevel, or miter> | loosely dotted | |
ultra thick (equal to 1.6pt) | double | ||
Examples | Example | Example | |
\draw[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 command [edit | edit source]
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
- Using the \path command.
- Using the \node command.
\node (Name of node) at (coordinates) [define node style, optional] {Text to appear};
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}
- Using the keyword node with other command viz. \draw command.
\draw (0,0) node{a} -- (1,1) node {b};
node[<options>](<name>){<text>}
The "(<name>)
" is a name for later reference and it is optional. If you only want to name a certain position without writing text there are two possibilities:
node[<options>](<name>){} coordinate[<options>](<name>)
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; |
|
Possible options for the node command are e.g. "inner sep=<dimension>
", "outer sep=<dimension>
", "minimum size=<dimension>
", "shape aspect=<aspect ratio>
", "text=<color>
", "font=
", "align=<left_right_center>
" A node is centered at the current coordinate by default. Often it would be better to have the node placed beside the actual coordinate: Right ("right
" or "anchor=west
"), left ("left
" or "anchor=east
"), above ("above
" or "anchor=south
"), below ("below
" or "anchor=north
"). Combinations are also possible, like "anchor=north east
" or "below left
".
\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)
".
Special commands [edit | edit source]
Tikzstyle [edit | edit source]
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}
Scope [edit | edit source]
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}
Loop [edit | edit source]
A loop can be realized by "\foreach ⟨variable⟩ in {⟨list of values⟩} ⟨commands⟩
".
\foreach \x in {0,...,9} \draw (\x,0) circle (0.4); |
|
PGF [edit | edit source]
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)}); |
|
Examples [edit | edit source]
Example 1 [edit | edit source]
\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 2 [edit | edit source]
\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 Torus [edit | edit source]
\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 functions [edit | edit source]
\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} |
|
Source: https://en.wikibooks.org/wiki/LaTeX/PGF/TikZ
Belum ada Komentar untuk "Draw Rectangle Onto the Tree Tikz"
Posting Komentar