Debian Codegraph @

texmf-dist/doc/generic/pgf/pgfmanual-en-tutorial.tex

raw
1 % Copyright 2019 by Till Tantau
2 %
3 % This file may be distributed and/or modified
4 %
5 % 1. under the LaTeX Project Public License and/or
6 % 2. under the GNU Free Documentation License.
7 %
8 % See the file doc/generic/pgf/licenses/LICENSE for more details.
9
10
11 \section{Tutorial: A Picture for Karl's Students}
12
13 This tutorial is intended for new users of \tikzname. It does not give an
14 exhaustive account of all the features of \tikzname, just of those that you are
15 likely to use right away.
16
17 Karl is a math and chemistry high-school teacher. He used to create the
18 graphics in his worksheets and exams using \LaTeX's |{picture}| environment.
19 While the results were acceptable, creating the graphics often turned out to be
20 a lengthy process. Also, there tended to be problems with lines having slightly
21 wrong angles and circles also seemed to be hard to get right. Naturally, his
22 students could not care less whether the lines had the exact right angles and
23 they find Karl's exams too difficult no matter how nicely they were drawn. But
24 Karl was never entirely satisfied with the result.
25
26 Karl's son, who was even less satisfied with the results (he did not have to
27 take the exams, after all), told Karl that he might wish to try out a new
28 package for creating graphics. A bit confusingly, this package seems to have
29 two names: First, Karl had to download and install a package called \pgfname.
30 Then it turns out that inside this package there is another package called
31 \tikzname, which is supposed to stand for ``\tikzname\ ist \emph{kein}
32 Zeichenprogramm''. Karl finds this all a bit strange and \tikzname\ seems to
33 indicate that the package does not do what he needs. However, having used
34 \textsc{gnu} software for quite some time and ``\textsc{gnu} not being Unix'',
35 there seems to be hope yet. His son assures him that \tikzname's name is
36 intended to warn people that \tikzname\ is not a program that you can use to
37 draw graphics with your mouse or tablet. Rather, it is more like a ``graphics
38 language''.
39
40
41 \subsection{Problem Statement}
42
43 Karl wants to put a graphic on the next worksheet for his students. He is
44 currently teaching his students about sine and cosine. What he would like to
45 have is something that looks like this (ideally):
46 %
47 \noindent
48 \begin{tikzpicture}
49 [scale=3,line cap=round,
50 % Styles
51 axes/.style=,
52 important line/.style={very thick},
53 information text/.style={rounded corners,fill=red!10,inner sep=1ex}]
54
55 % Local definitions
56 \def\costhirty{0.8660256}
57
58 % Colors
59 \colorlet{anglecolor}{green!50!black}
60 \colorlet{sincolor}{red}
61 \colorlet{tancolor}{orange!80!black}
62 \colorlet{coscolor}{blue}
63
64 % The graphic
65 \draw[help lines,step=0.5cm] (-1.4,-1.4) grid (1.4,1.4);
66
67 \draw (0,0) circle [radius=1cm];
68
69 \begin{scope}[axes]
70 \draw[->] (-1.5,0) -- (1.5,0) node[right] {$x$};
71 \draw[->] (0,-1.5) -- (0,1.5) node[above] {$y$};
72
73 \foreach \x/\xtext in {-1, -.5/-\frac{1}{2}, 1}
74 \draw[xshift=\x cm] (0pt,1pt) -- (0pt,-1pt) node[below,fill=white] {$\xtext$};
75
76 \foreach \y/\ytext in {-1, -.5/-\frac{1}{2}, .5/\frac{1}{2}, 1}
77 \draw[yshift=\y cm] (1pt,0pt) -- (-1pt,0pt) node[left,fill=white] {$\ytext$};
78 \end{scope}
79
80 \filldraw[fill=green!20,draw=anglecolor] (0,0) -- (3mm,0pt) arc(0:30:3mm);
81 \draw (15:2mm) node[anglecolor] {$\alpha$};
82
83 \draw[important line,sincolor]
84 (30:1cm) -- node[left=1pt,fill=white] {$\sin \alpha$} +(0,-.5);
85
86 \draw[important line,coscolor]
87 (0,0) -- node[below=2pt,fill=white] {$\cos \alpha$} (\costhirty,0);
88
89 \draw[important line,tancolor] (1,0) --
90 node [right=1pt,fill=white]
91 {
92 $\displaystyle \tan \alpha \color{black}=
93 \frac{{\color{sincolor}\sin \alpha}}{\color{coscolor}\cos \alpha}$
94 } (intersection of 0,0--30:1cm and 1,0--1,1) coordinate (t);
95
96 \draw (0,0) -- (t);
97
98 \draw[xshift=1.85cm] node [right,text width=6cm,information text]
99 {
100 The {\color{anglecolor} angle $\alpha$} is $30^\circ$ in the
101 example ($\pi/6$ in radians). The {\color{sincolor}sine of
102 $\alpha$}, which is the height of the red line, is
103 \[
104 {\color{sincolor} \sin \alpha} = 1/2.
105 \]
106 By the Theorem of Pythagoras we have ${\color{coscolor}\cos^2 \alpha} +
107 {\color{sincolor}\sin^2\alpha} =1$. Thus the length of the blue
108 line, which is the {\color{coscolor}cosine of $\alpha$}, must be
109 \[
110 {\color{coscolor}\cos\alpha} = \sqrt{1 - 1/4} = \textstyle
111 \frac{1}{2} \sqrt 3.
112 \]%
113 This shows that {\color{tancolor}$\tan \alpha$}, which is the
114 height of the orange line, is
115 \[
116 {\color{tancolor}\tan\alpha} = \frac{{\color{sincolor}\sin
117 \alpha}}{\color{coscolor}\cos \alpha} = 1/\sqrt 3.
118 \]%
119 };
120 \end{tikzpicture}
121
122
123 \subsection{Setting up the Environment}
124
125 In \tikzname, to draw a picture, at the start of the picture you need to tell
126 \TeX\ or \LaTeX\ that you want to start a picture. In \LaTeX\ this is done
127 using the environment |{tikzpicture}|, in plain \TeX\ you just use
128 |\tikzpicture| to start the picture and |\endtikzpicture| to end it.
129
130
131 \subsubsection{Setting up the Environment in \LaTeX}
132
133 Karl, being a \LaTeX\ user, thus sets up his file as follows:
134 %
135 \begin{codeexample}[code only]
136 \documentclass{article} % say
137 \usepackage{tikz}
138 \begin{document}
139 We are working on
140 \begin{tikzpicture}
141 \draw (-1.5,0) -- (1.5,0);
142 \draw (0,-1.5) -- (0,1.5);
143 \end{tikzpicture}.
144 \end{document}
145 \end{codeexample}
146
147 When executed, that is, run via |pdflatex| or via |latex| followed by |dvips|,
148 the resulting will contain something that looks like this:
149 %
150 \begin{codeexample}[width=7cm]
151 We are working on
152 \begin{tikzpicture}
153 \draw (-1.5,0) -- (1.5,0);
154 \draw (0,-1.5) -- (0,1.5);
155 \end{tikzpicture}.
156 \end{codeexample}
157
158 Admittedly, not quite the whole picture, yet, but we do have the axes
159 established. Well, not quite, but we have the lines that make up the axes
160 drawn. Karl suddenly has a sinking feeling that the picture is still some way
161 off.
162
163 Let's have a more detailed look at the code. First, the package |tikz| is
164 loaded. This package is a so-called ``frontend'' to the basic \pgfname\ system.
165 The basic layer, which is also described in this manual, is somewhat more,
166 well, basic and thus harder to use. The frontend makes things easier by
167 providing a simpler syntax.
168
169 Inside the environment there are two |\draw| commands. They mean: ``The path,
170 which is specified following the command up to the semicolon, should be
171 drawn.'' The first path is specified as |(-1.5,0) -- (1.5,0)|, which means ``a
172 straight line from the point at position $(-1.5,0)$ to the point at position
173 $(1.5,0)$''. Here, the positions are specified within a special coordinate
174 system in which, initially, one unit is 1cm.
175
176 Karl is quite pleased to note that the environment automatically reserves
177 enough space to encompass the picture.
178
179
180 \subsubsection{Setting up the Environment in Plain \TeX}
181
182 Karl's wife Gerda, who also happens to be a math teacher, is not a \LaTeX\
183 user, but uses plain \TeX\ since she prefers to do things ``the old way''. She
184 can also use \tikzname. Instead of |\usepackage{tikz}| she has to write
185 |\input tikz.tex| and instead of |\begin{tikzpicture}| she writes
186 |\tikzpicture| and instead of |\end{tikzpicture}| she writes |\endtikzpicture|.
187
188 Thus, she would use:
189 %
190 \begin{codeexample}[code only]
191 %% Plain TeX file
192 \input tikz.tex
193 \baselineskip=12pt
194 \hsize=6.3truein
195 \vsize=8.7truein
196 We are working on
197 \tikzpicture
198 \draw (-1.5,0) -- (1.5,0);
199 \draw (0,-1.5) -- (0,1.5);
200 \endtikzpicture.
201 \bye
202 \end{codeexample}
203
204 Gerda can typeset this file using either |pdftex| or |tex| together with
205 |dvips|. \tikzname\ will automatically discern which driver she is using. If
206 she wishes to use |dvipdfm| together with |tex|, she either needs to modify the
207 file |pgf.cfg| or can write |\def\pgfsysdriver{pgfsys-dvipdfm.def}| somewhere
208 \emph{before} she inputs |tikz.tex| or |pgf.tex|.
209
210
211 \subsubsection{Setting up the Environment in Con\TeX t}
212
213 Karl's uncle Hans uses Con\TeX t. Like Gerda, Hans can also use \tikzname.
214 Instead of |\usepackage{tikz}| he says |\usemodule[tikz]|. Instead of
215 |\begin{tikzpicture}| he writes |\starttikzpicture| and instead of
216 |\end{tikzpicture}| he writes |\stoptikzpicture|.
217
218 His version of the example looks like this:
219 %
220 \begin{codeexample}[code only]
221 %% ConTeXt file
222 \usemodule[tikz]
223
224 \starttext
225 We are working on
226 \starttikzpicture
227 \draw (-1.5,0) -- (1.5,0);
228 \draw (0,-1.5) -- (0,1.5);
229 \stoptikzpicture.
230 \stoptext
231 \end{codeexample}
232
233 Hans will now typeset this file in the usual way using |texexec| or |context|.
234
235
236 \subsection{Straight Path Construction}
237
238 The basic building block of all pictures in \tikzname\ is the path. A
239 \emph{path} is a series of straight lines and curves that are connected (that
240 is not the whole picture, but let us ignore the complications for the moment).
241 You start a path by specifying the coordinates of the start position as a point
242 in round brackets, as in |(0,0)|. This is followed by a series of ``path
243 extension operations''. The simplest is |--|, which we used already. It must be
244 followed by another coordinate and it extends the path in a straight line to
245 this new position. For example, if we were to turn the two paths of the axes
246 into one path, the following would result:
247 %
248 \begin{codeexample}[]
249 \tikz \draw (-1.5,0) -- (1.5,0) -- (0,-1.5) -- (0,1.5);
250 \end{codeexample}
251
252 Karl is a bit confused by the fact that there is no |{tikzpicture}|
253 environment, here. Instead, the little command |\tikz| is used. This command
254 either takes one argument (starting with an opening brace as in
255 |\tikz{\draw (0,0) -- (1.5,0)}|, which yields \tikz{\draw (0,0) --(1.5,0);}) or
256 collects everything up to the next semicolon and puts it inside a
257 |{tikzpicture}| environment. As a rule of thumb, all \tikzname\ graphic drawing
258 commands must occur as an argument of |\tikz| or inside a |{tikzpicture}|
259 environment. Fortunately, the command |\draw| will only be defined inside this
260 environment, so there is little chance that you will accidentally do something
261 wrong here.
262
263
264 \subsection{Curved Path Construction}
265
266 The next thing Karl wants to do is to draw the circle. For this, straight lines
267 obviously will not do. Instead, we need some way to draw curves. For this,
268 \tikzname\ provides a special syntax. One or two ``control points'' are needed.
269 The math behind them is not quite trivial, but here is the basic idea: Suppose
270 you are at point $x$ and the first control point is $y$. Then the curve will
271 start ``going in the direction of~$y$ at~$x$'', that is, the tangent of the
272 curve at $x$ will point toward~$y$. Next, suppose the curve should end at $z$
273 and the second support point is $w$. Then the curve will, indeed, end at $z$
274 and the tangent of the curve at point $z$ will go through $w$.
275
276 Here is an example (the control points have been added for clarity):
277 %
278 \begin{codeexample}[]
279 \begin{tikzpicture}
280 \filldraw [gray] (0,0) circle [radius=2pt]
281 (1,1) circle [radius=2pt]
282 (2,1) circle [radius=2pt]
283 (2,0) circle [radius=2pt];
284 \draw (0,0) .. controls (1,1) and (2,1) .. (2,0);
285 \end{tikzpicture}
286 \end{codeexample}
287
288 The general syntax for extending a path in a ``curved'' way is |.. controls|
289 \meta{first control point} |and| \meta{second control point} |..|
290 \meta{end point}. You can leave out the |and| \meta{second control point},
291 which causes the first one to be used twice.
292
293 So, Karl can now add the first half circle to the picture:
294 %
295 \begin{codeexample}[]
296 \begin{tikzpicture}
297 \draw (-1.5,0) -- (1.5,0);
298 \draw (0,-1.5) -- (0,1.5);
299 \draw (-1,0) .. controls (-1,0.555) and (-0.555,1) .. (0,1)
300 .. controls (0.555,1) and (1,0.555) .. (1,0);
301 \end{tikzpicture}
302 \end{codeexample}
303
304 Karl is happy with the result, but finds specifying circles in this way to be
305 extremely awkward. Fortunately, there is a much simpler way.
306
307
308 \subsection{Circle Path Construction}
309
310 In order to draw a circle, the path construction operation |circle| can be
311 used. This operation is followed by a radius in brackets as in the following
312 example: (Note that the previous position is used as the \emph{center} of the
313 circle.)
314 %
315 \begin{codeexample}[]
316 \tikz \draw (0,0) circle [radius=10pt];
317 \end{codeexample}
318
319 You can also append an ellipse to the path using the |ellipse| operation.
320 Instead of a single radius you can specify two of them:
321 %
322 \begin{codeexample}[]
323 \tikz \draw (0,0) ellipse [x radius=20pt, y radius=10pt];
324 \end{codeexample}
325
326 To draw an ellipse whose axes are not horizontal and vertical, but point in an
327 arbitrary direction (a ``turned ellipse'' like \tikz \draw[rotate=30] (0,0)
328 ellipse [x radius=6pt, y radius=3pt];) you can use transformations, which are
329 explained later. The code for the little ellipse is
330 |\tikz \draw[rotate=30] (0,0) ellipse [x radius=6pt, y radius=3pt];|, by the
331 way.
332
333 So, returning to Karl's problem, he can write
334 |\draw (0,0) circle [radius=1cm];| to draw the circle:
335 %
336 \begin{codeexample}[]
337 \begin{tikzpicture}
338 \draw (-1.5,0) -- (1.5,0);
339 \draw (0,-1.5) -- (0,1.5);
340 \draw (0,0) circle [radius=1cm];
341 \end{tikzpicture}
342 \end{codeexample}
343
344 At this point, Karl is a bit alarmed that the circle is so small when he wants
345 the final picture to be much bigger. He is pleased to learn that \tikzname\ has
346 powerful transformation options and scaling everything by a factor of three is
347 very easy. But let us leave the size as it is for the moment to save some
348 space.
349
350
351 \subsection{Rectangle Path Construction}
352
353 The next things we would like to have is the grid in the background. There are
354 several ways to produce it. For example, one might draw lots of rectangles.
355 Since rectangles are so common, there is a special syntax for them: To add a
356 rectangle to the current path, use the |rectangle| path construction operation.
357 This operation should be followed by another coordinate and will append a
358 rectangle to the path such that the previous coordinate and the next
359 coordinates are corners of the rectangle. So, let us add two rectangles to the
360 picture:
361 %
362 \begin{codeexample}[]
363 \begin{tikzpicture}
364 \draw (-1.5,0) -- (1.5,0);
365 \draw (0,-1.5) -- (0,1.5);
366 \draw (0,0) circle [radius=1cm];
367 \draw (0,0) rectangle (0.5,0.5);
368 \draw (-0.5,-0.5) rectangle (-1,-1);
369 \end{tikzpicture}
370 \end{codeexample}
371
372 While this may be nice in other situations, this is not really leading anywhere
373 with Karl's problem: First, we would need an awful lot of these rectangles and
374 then there is the border that is not ``closed''.
375
376 So, Karl is about to resort to simply drawing four vertical and four horizontal
377 lines using the nice |\draw| command, when he learns that there is a |grid|
378 path construction operation.
379
380
381 \subsection{Grid Path Construction}
382
383 The |grid| path operation adds a grid to the current path. It will add lines
384 making up a grid that fills the rectangle whose one corner is the current point
385 and whose other corner is the point following the |grid| operation. For
386 example, the code |\tikz \draw[step=2pt] (0,0) grid (10pt,10pt);| produces
387 \tikz \draw[step=2pt] (0,0) grid (10pt,10pt);. Note how the optional argument
388 for |\draw| can be used to specify a grid width (there are also |xstep| and
389 |ystep| to define the steppings independently). As Karl will learn soon, there
390 are \emph{lots} of things that can be influenced using such options.
391
392 For Karl, the following code could be used:
393 %
394 \begin{codeexample}[]
395 \begin{tikzpicture}
396 \draw (-1.5,0) -- (1.5,0);
397 \draw (0,-1.5) -- (0,1.5);
398 \draw (0,0) circle [radius=1cm];
399 \draw[step=.5cm] (-1.4,-1.4) grid (1.4,1.4);
400 \end{tikzpicture}
401 \end{codeexample}
402
403 Having another look at the desired picture, Karl notices that it would be nice
404 for the grid to be more subdued. (His son told him that grids tend to be
405 distracting if they are not subdued.) To subdue the grid, Karl adds two more
406 options to the |\draw| command that draws the grid. First, he uses the color
407 |gray| for the grid lines. Second, he reduces the line width to |very thin|.
408 Finally, he swaps the ordering of the commands so that the grid is drawn first
409 and everything else on top.
410 %
411 \begin{codeexample}[]
412 \begin{tikzpicture}
413 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
414 \draw (-1.5,0) -- (1.5,0);
415 \draw (0,-1.5) -- (0,1.5);
416 \draw (0,0) circle [radius=1cm];
417 \end{tikzpicture}
418 \end{codeexample}
419
420
421 \subsection{Adding a Touch of Style}
422
423 Instead of the options |gray,very thin| Karl could also have said |help lines|.
424 \emph{Styles} are predefined sets of options that can be used to organize how a
425 graphic is drawn. By saying |help lines| you say ``use the style that I (or
426 someone else) has set for drawing help lines''. If Karl decides, at some later
427 point, that grids should be drawn, say, using the color |blue!50| instead of
428 |gray|, he could provide the following option somewhere:
429 %
430 \begin{codeexample}[code only]
431 help lines/.style={color=blue!50,very thin}
432 \end{codeexample}
433 %
434 The effect of this ``style setter'' is that in the current scope or environment
435 the |help lines| option has the same effect as |color=blue!50,very thin|.
436
437 Using styles makes your graphics code more flexible. You can change the way
438 things look easily in a consistent manner. Normally, styles are defined at the
439 beginning of a picture. However, you may sometimes wish to define a style
440 globally, so that all pictures of your document can use this style. Then you
441 can easily change the way all graphics look by changing this one style. In this
442 situation you can use the |\tikzset| command at the beginning of the document
443 as in
444 %
445 \begin{codeexample}[code only]
446 \tikzset{help lines/.style=very thin}
447 \end{codeexample}
448
449 To build a hierarchy of styles you can have one style use another. So in order
450 to define a style |Karl's grid| that is based on the |grid| style Karl could
451 say
452 %
453 \begin{codeexample}[code only]
454 \tikzset{Karl's grid/.style={help lines,color=blue!50}}
455 ...
456 \draw[Karl's grid] (0,0) grid (5,5);
457 \end{codeexample}
458
459 Styles are made even more powerful by parametrization. This means that, like
460 other options, styles can also be used with a parameter. For instance, Karl
461 could parameterize his grid so that, by default, it is blue, but he could also
462 use another color.
463 %
464 \begin{codeexample}[code only]
465 \begin{tikzpicture}
466 [Karl's grid/.style ={help lines,color=#1!50},
467 Karl's grid/.default=blue]
468
469 \draw[Karl's grid] (0,0) grid (1.5,2);
470 \draw[Karl's grid=red] (2,0) grid (3.5,2);
471 \end{tikzpicture}
472 \end{codeexample}
473
474 In this example, the definition of the style |Karl's grid| is given as an
475 optional argument to the |{tikzpicture}| environment. Additional styles for other
476 elements would follow after a comma. With many styles in effect, the optional
477 argument of the environment may easily happen to be longer than the actual
478 contents.
479
480 \subsection{Drawing Options}
481
482 Karl wonders what other options there are that influence how a path is drawn.
483 He saw already that the |color=|\meta{color} option can be used to set the
484 line's color. The option |draw=|\meta{color} does nearly the same, only it sets
485 the color for the lines only and a different color can be used for filling
486 (Karl will need this when he fills the arc for the angle).
487
488 He saw that the style |very thin| yields very thin lines. Karl is not really
489 surprised by this and neither is he surprised to learn that |thin| yields thin
490 lines, |thick| yields thick lines, |very thick| yields very thick lines,
491 |ultra thick| yields really, really thick lines and |ultra thin| yields lines
492 that are so thin that low-resolution printers and displays will have trouble
493 showing them. He wonders what gives lines of ``normal'' thickness. It turns out
494 that |thin| is the correct choice, since it gives the same thickness as \TeX's
495 |\hrule| command. Nevertheless, Karl would like to know whether there is
496 anything ``in the middle'' between |thin| and |thick|. There is: |semithick|.
497
498 Another useful thing one can do with lines is to dash or dot them. For this,
499 the two styles |dashed| and |dotted| can be used, yielding \tikz[baseline]
500 \draw[dashed] (0,.5ex) -- ++(2em,0pt); and \tikz[baseline] \draw[dotted]
501 (0,.5ex) -- ++(2em,0pt);. Both options also exist in a loose and a dense
502 version, called |loosely dashed|, |densely dashed|, |loosely dotted|, and
503 |densely dotted|. If he really, really needs to, Karl can also define much
504 more complex dashing patterns with the |dash pattern| option, but his son
505 insists that dashing is to be used with utmost care and mostly distracts.
506 Karl's son claims that complicated dashing patterns are evil. Karl's students
507 do not care about dashing patterns.
508
509
510 \subsection{Arc Path Construction}
511
512 Our next obstacle is to draw the arc for the angle. For this, the |arc| path
513 construction operation is useful, which draws part of a circle or ellipse. This
514 |arc| operation is followed by options in brackets that specify the arc. An
515 example would be \texttt{arc[start angle=10, end angle=80, radius=10pt]}, which
516 means exactly what it says. Karl obviously needs an arc from $0^\circ$ to
517 $30^\circ$. The radius should be something relatively small, perhaps around one
518 third of the circle's radius. When one uses the arc path construction
519 operation, the specified arc will be added with its starting point at the
520 current position. So, we first have to ``get there''.
521 %
522 \begin{codeexample}[]
523 \begin{tikzpicture}
524 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
525 \draw (-1.5,0) -- (1.5,0);
526 \draw (0,-1.5) -- (0,1.5);
527 \draw (0,0) circle [radius=1cm];
528 \draw (3mm,0mm) arc [start angle=0, end angle=30, radius=3mm];
529 \end{tikzpicture}
530 \end{codeexample}
531
532 Karl thinks this is really a bit small and he cannot continue unless he learns
533 how to do scaling. For this, he can add the |[scale=3]| option. He could add
534 this option to each |\draw| command, but that would be awkward. Instead, he
535 adds it to the whole environment, which causes this option to apply to
536 everything within.
537 %
538 \begin{codeexample}[]
539 \begin{tikzpicture}[scale=3]
540 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
541 \draw (-1.5,0) -- (1.5,0);
542 \draw (0,-1.5) -- (0,1.5);
543 \draw (0,0) circle [radius=1cm];
544 \draw (3mm,0mm) arc [start angle=0, end angle=30, radius=3mm];
545 \end{tikzpicture}
546 \end{codeexample}
547
548 As for circles, you can specify ``two'' radii in order to get an elliptical
549 arc.
550 %
551 \begin{codeexample}[]
552 \tikz \draw (0,0)
553 arc [start angle=0, end angle=315,
554 x radius=1.75cm, y radius=1cm];
555 \end{codeexample}
556
557
558 \subsection{Clipping a Path}
559
560 In order to save space in this manual, it would be nice to clip Karl's graphics
561 a bit so that we can focus on the ``interesting'' parts. Clipping is pretty
562 easy in \tikzname. You can use the |\clip| command to clip all subsequent
563 drawing. It works like |\draw|, only it does not draw anything, but uses the
564 given path to clip everything subsequently.
565 %
566 \begin{codeexample}[]
567 \begin{tikzpicture}[scale=3]
568 \clip (-0.1,-0.2) rectangle (1.1,0.75);
569 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
570 \draw (-1.5,0) -- (1.5,0);
571 \draw (0,-1.5) -- (0,1.5);
572 \draw (0,0) circle [radius=1cm];
573 \draw (3mm,0mm) arc [start angle=0, end angle=30, radius=3mm];
574 \end{tikzpicture}
575 \end{codeexample}
576
577 You can also do both at the same time: Draw \emph{and} clip a path. For this,
578 use the |\draw| command and add the |clip| option. (This is not the whole
579 picture: You can also use the |\clip| command and add the |draw| option. Well,
580 that is also not the whole picture: In reality, |\draw| is just a shorthand for
581 |\path[draw]| and |\clip| is a shorthand for |\path[clip]| and you could also
582 say |\path[draw,clip]|.) Here is an example:
583 %
584 \begin{codeexample}[]
585 \begin{tikzpicture}[scale=3]
586 \clip[draw] (0.5,0.5) circle (.6cm);
587 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
588 \draw (-1.5,0) -- (1.5,0);
589 \draw (0,-1.5) -- (0,1.5);
590 \draw (0,0) circle [radius=1cm];
591 \draw (3mm,0mm) arc [start angle=0, end angle=30, radius=3mm];
592 \end{tikzpicture}
593 \end{codeexample}
594
595
596 \subsection{Parabola and Sine Path Construction}
597
598 Although Karl does not need them for his picture, he is pleased to learn that
599 there are |parabola| and |sin| and |cos| path operations for adding parabolas
600 and sine and cosine curves to the current path. For the |parabola| operation,
601 the current point will lie on the parabola as well as the point given after the
602 parabola operation. Consider the following example:
603 %
604 \begin{codeexample}[]
605 \tikz \draw (0,0) rectangle (1,1) (0,0) parabola (1,1);
606 \end{codeexample}
607
608 It is also possible to place the bend somewhere else:
609 %
610 \begin{codeexample}[]
611 \tikz \draw[x=1pt,y=1pt] (0,0) parabola bend (4,16) (6,12);
612 \end{codeexample}
613
614 The operations |sin| and |cos| add a sine or cosine curve in the interval
615 $[0,\pi/2]$ such that the previous current point is at the start of the curve
616 and the curve ends at the given end point. Here are two examples:
617 %
618 \begin{codeexample}[]
619 A sine \tikz \draw[x=1ex,y=1ex] (0,0) sin (1.57,1); curve.
620 \end{codeexample}
621
622 \begin{codeexample}[]
623 \tikz \draw[x=1.57ex,y=1ex] (0,0) sin (1,1) cos (2,0) sin (3,-1) cos (4,0)
624 (0,1) cos (1,0) sin (2,-1) cos (3,0) sin (4,1);
625 \end{codeexample}
626
627
628 \subsection{Filling and Drawing}
629
630 Returning to the picture, Karl now wants the angle to be ``filled'' with a very
631 light green. For this he uses |\fill| instead of |\draw|. Here is what Karl
632 does:
633 %
634 \begin{codeexample}[]
635 \begin{tikzpicture}[scale=3]
636 \clip (-0.1,-0.2) rectangle (1.1,0.75);
637 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
638 \draw (-1.5,0) -- (1.5,0);
639 \draw (0,-1.5) -- (0,1.5);
640 \draw (0,0) circle [radius=1cm];
641 \fill[green!20!white] (0,0) -- (3mm,0mm)
642 arc [start angle=0, end angle=30, radius=3mm] -- (0,0);
643 \end{tikzpicture}
644 \end{codeexample}
645
646 The color |green!20!white| means 20\% green and 80\% white mixed together. Such
647 color expression are possible since \tikzname\ uses Uwe Kern's |xcolor|
648 package, see the documentation of that package for details on color
649 expressions.
650
651 What would have happened, if Karl had not ``closed'' the path using |--(0,0)|
652 at the end? In this case, the path is closed automatically, so this could have
653 been omitted. Indeed, it would even have been better to write the following,
654 instead:
655 %
656 \begin{codeexample}[code only]
657 \fill[green!20!white] (0,0) -- (3mm,0mm)
658 arc [start angle=0, end angle=30, radius=3mm] -- cycle;
659 \end{codeexample}
660 %
661 The |--cycle| causes the current path to be closed (actually the current part
662 of the current path) by smoothly joining the first and last point. To
663 appreciate the difference, consider the following example:
664 %
665 \begin{codeexample}[]
666 \begin{tikzpicture}[line width=5pt]
667 \draw (0,0) -- (1,0) -- (1,1) -- (0,0);
668 \draw (2,0) -- (3,0) -- (3,1) -- cycle;
669 \useasboundingbox (0,1.5); % make bounding box higher
670 \end{tikzpicture}
671 \end{codeexample}
672
673 You can also fill and draw a path at the same time using the |\filldraw|
674 command. This will first draw the path, then fill it. This may not seem too
675 useful, but you can specify different colors to be used for filling and for
676 stroking. These are specified as optional arguments like this:
677 %
678 \begin{codeexample}[]
679 \begin{tikzpicture}[scale=3]
680 \clip (-0.1,-0.2) rectangle (1.1,0.75);
681 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
682 \draw (-1.5,0) -- (1.5,0);
683 \draw (0,-1.5) -- (0,1.5);
684 \draw (0,0) circle [radius=1cm];
685 \filldraw[fill=green!20!white, draw=green!50!black] (0,0) -- (3mm,0mm)
686 arc [start angle=0, end angle=30, radius=3mm] -- cycle;
687 \end{tikzpicture}
688 \end{codeexample}
689
690
691 \subsection{Shading}
692
693 Karl briefly considers the possibility of making the angle ``more fancy'' by
694 \emph{shading} it. Instead of filling the area with a uniform color, a smooth
695 transition between different colors is used. For this, |\shade| and
696 |\shadedraw|, for shading and drawing at the same time, can be used:
697 %
698 \begin{codeexample}[]
699 \tikz \shade (0,0) rectangle (2,1) (3,0.5) circle (.5cm);
700 \end{codeexample}
701 %
702 The default shading is a smooth transition from gray to white. To specify
703 different colors, you can use options:
704 %
705 \begin{codeexample}[]
706 \begin{tikzpicture}[rounded corners,ultra thick]
707 \shade[top color=yellow,bottom color=black] (0,0) rectangle +(2,1);
708 \shade[left color=yellow,right color=black] (3,0) rectangle +(2,1);
709 \shadedraw[inner color=yellow,outer color=black,draw=yellow] (6,0) rectangle +(2,1);
710 \shade[ball color=green] (9,.5) circle (.5cm);
711 \end{tikzpicture}
712 \end{codeexample}
713
714 For Karl, the following might be appropriate:
715 %
716 \begin{codeexample}[]
717 \begin{tikzpicture}[scale=3]
718 \clip (-0.1,-0.2) rectangle (1.1,0.75);
719 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
720 \draw (-1.5,0) -- (1.5,0);
721 \draw (0,-1.5) -- (0,1.5);
722 \draw (0,0) circle [radius=1cm];
723 \shadedraw[left color=gray,right color=green, draw=green!50!black]
724 (0,0) -- (3mm,0mm)
725 arc [start angle=0, end angle=30, radius=3mm] -- cycle;
726 \end{tikzpicture}
727 \end{codeexample}
728
729 However, he wisely decides that shadings usually only distract without adding
730 anything to the picture.
731
732
733 \subsection{Specifying Coordinates}
734
735 Karl now wants to add the sine and cosine lines. He knows already that he can
736 use the |color=| option to set the lines' colors. So, what is the best way to
737 specify the coordinates?
738
739 There are different ways of specifying coordinates. The easiest way is to say
740 something like |(10pt,2cm)|. This means 10pt in $x$-direction and 2cm in
741 $y$-directions. Alternatively, you can also leave out the units as in |(1,2)|,
742 which means ``one times the current $x$-vector plus twice the current
743 $y$-vector''. These vectors default to 1cm in the $x$-direction and 1cm in the
744 $y$-direction, respectively.
745
746 In order to specify points in polar coordinates, use the notation |(30:1cm)|,
747 which means 1cm in direction 30 degree. This is obviously quite useful to ``get
748 to the point $(\cos 30^\circ,\sin 30^\circ)$ on the circle''.
749
750 You can add a single |+| sign in front of a coordinate or two of them as in
751 |+(0cm,1cm)| or |++(2cm,0cm)|. Such coordinates are interpreted differently:
752 The first form means ``1cm upwards from the previous specified position'' and
753 the second means ``2cm to the right of the previous specified position, making
754 this the new specified position''. For example, we can draw the sine line as
755 follows:
756 %
757 \begin{codeexample}[]
758 \begin{tikzpicture}[scale=3]
759 \clip (-0.1,-0.2) rectangle (1.1,0.75);
760 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
761 \draw (-1.5,0) -- (1.5,0);
762 \draw (0,-1.5) -- (0,1.5);
763 \draw (0,0) circle [radius=1cm];
764 \filldraw[fill=green!20,draw=green!50!black] (0,0) -- (3mm,0mm)
765 arc [start angle=0, end angle=30, radius=3mm] -- cycle;
766 \draw[red,very thick] (30:1cm) -- +(0,-0.5);
767 \end{tikzpicture}
768 \end{codeexample}
769
770 Karl used the fact $\sin 30^\circ = 1/2$. However, he very much doubts that his
771 students know this, so it would be nice to have a way of specifying ``the point
772 straight down from |(30:1cm)| that lies on the $x$-axis''. This is, indeed,
773 possible using a special syntax: Karl can write \verb!(30:1cm |- 0,0)!. In
774 general, the meaning of |(|\meta{p}\verb! |- !\meta{q}|)| is ``the intersection
775 of a vertical line through $p$ and a horizontal line through $q$''.
776
777 Next, let us draw the cosine line. One way would be to say
778 \verb!(30:1cm |- 0,0) -- (0,0)!. Another way is the following: we ``continue''
779 from where the sine ends:
780 %
781 \begin{codeexample}[]
782 \begin{tikzpicture}[scale=3]
783 \clip (-0.1,-0.2) rectangle (1.1,0.75);
784 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
785 \draw (-1.5,0) -- (1.5,0);
786 \draw (0,-1.5) -- (0,1.5);
787 \draw (0,0) circle [radius=1cm];
788 \filldraw[fill=green!20,draw=green!50!black] (0,0) -- (3mm,0mm)
789 arc [start angle=0, end angle=30, radius=3mm] -- cycle;
790 \draw[red,very thick] (30:1cm) -- +(0,-0.5);
791 \draw[blue,very thick] (30:1cm) ++(0,-0.5) -- (0,0);
792 \end{tikzpicture}
793 \end{codeexample}
794
795 Note that there is no |--| between |(30:1cm)| and |++(0,-0.5)|. In detail, this
796 path is interpreted as follows: ``First, the |(30:1cm)| tells me to move my pen
797 to $(\cos 30^\circ,1/2)$. Next, there comes another coordinate specification,
798 so I move my pen there without drawing anything. This new point is half a unit
799 down from the last position, thus it is at $(\cos 30^\circ,0)$. Finally, I move
800 the pen to the origin, but this time drawing something (because of the |--|).''
801
802 To appreciate the difference between |+| and |++| consider the following
803 example:
804 %
805 \begin{codeexample}[]
806 \begin{tikzpicture}
807 \def\rectanglepath{-- ++(1cm,0cm) -- ++(0cm,1cm) -- ++(-1cm,0cm) -- cycle}
808 \draw (0,0) \rectanglepath;
809 \draw (1.5,0) \rectanglepath;
810 \end{tikzpicture}
811 \end{codeexample}
812
813 By comparison, when using a single |+|, the coordinates are different:
814 %
815 \begin{codeexample}[]
816 \begin{tikzpicture}
817 \def\rectanglepath{-- +(1cm,0cm) -- +(1cm,1cm) -- +(0cm,1cm) -- cycle}
818 \draw (0,0) \rectanglepath;
819 \draw (1.5,0) \rectanglepath;
820 \end{tikzpicture}
821 \end{codeexample}
822
823
824 Naturally, all of this could have been written more clearly and more
825 economically like this (either with a single or a double |+|):
826 %
827 \begin{codeexample}[]
828 \tikz \draw (0,0) rectangle +(1,1) (1.5,0) rectangle +(1,1);
829 \end{codeexample}
830
831
832 \subsection{Intersecting Paths}
833
834 Karl is left with the line for $\tan \alpha$, which seems difficult to specify
835 using transformations and polar coordinates. The first -- and easiest -- thing
836 he can do is so simply use the coordinate |(1,{tan(30)})| since \tikzname's
837 math engine knows how to compute things like |tan(30)|. Note the added braces
838 since, otherwise, \tikzname's parser would think that the first closing
839 parenthesis ends the coordinate (in general, you need to add braces around
840 components of coordinates when these components contain parentheses).
841
842 Karl can, however, also use a more elaborate, but also more ``geometric'' way
843 of computing the length of the orange line: He can specify intersections of
844 paths as coordinates. The line for $\tan \alpha$ starts at $(1,0)$ and goes
845 upward to a point that is at the intersection of a line going ``up'' and a line
846 going from the origin through |(30:1cm)|. Such computations are made available
847 by the |intersections| library.
848
849 What Karl must do is to create two ``invisible'' paths that intersect at the
850 position of interest. Creating paths that are not otherwise seen can be done
851 using the |\path| command without any options like |draw| or |fill|. Then, Karl
852 can add the |name path| option to the path for later reference. Once the paths
853 have been constructed, Karl can use the |name intersections| to assign names to
854 the coordinate for later reference.
855 %
856 \begin{codeexample}[code only]
857 \path [name path=upward line] (1,0) -- (1,1);
858 \path [name path=sloped line] (0,0) -- (30:1.5cm); % a bit longer, so that there is an intersection
859
860 % (add `\usetikzlibrary{intersections}' after loading tikz in the preamble)
861 \draw [name intersections={of=upward line and sloped line, by=x}]
862 [very thick,orange] (1,0) -- (x);
863 \end{codeexample}
864
865
866 \subsection{Adding Arrow Tips}
867
868 Karl now wants to add the little arrow tips at the end of the axes. He has
869 noticed that in many plots, even in scientific journals, these arrow tips seem
870 to be missing, presumably because the generating programs cannot produce them.
871 Karl thinks arrow tips belong at the end of axes. His son agrees. His students
872 do not care about arrow tips.
873
874 It turns out that adding arrow tips is pretty easy: Karl adds the option |->|
875 to the drawing commands for the axes:
876 %
877 \begin{codeexample}[preamble={\usetikzlibrary{intersections}}]
878 \begin{tikzpicture}[scale=3]
879 \clip (-0.1,-0.2) rectangle (1.1,1.51);
880 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
881 \draw[->] (-1.5,0) -- (1.5,0);
882 \draw[->] (0,-1.5) -- (0,1.5);
883 \draw (0,0) circle [radius=1cm];
884 \filldraw[fill=green!20,draw=green!50!black] (0,0) -- (3mm,0mm)
885 arc [start angle=0, end angle=30, radius=3mm] -- cycle;
886 \draw[red,very thick] (30:1cm) -- +(0,-0.5);
887 \draw[blue,very thick] (30:1cm) ++(0,-0.5) -- (0,0);
888
889 \path [name path=upward line] (1,0) -- (1,1);
890 \path [name path=sloped line] (0,0) -- (30:1.5cm);
891 \draw [name intersections={of=upward line and sloped line, by=x}]
892 [very thick,orange] (1,0) -- (x);
893 \end{tikzpicture}
894 \end{codeexample}
895
896 If Karl had used the option |<-| instead of |->|, arrow tips would have been
897 put at the beginning of the path. The option |<->| puts arrow tips at both ends
898 of the path.
899
900 There are certain restrictions to the kind of paths to which arrow tips can be
901 added. As a rule of thumb, you can add arrow tips only to a single open
902 ``line''. For example, you cannot add tips to, say, a rectangle or a circle.
903 However, you can add arrow tips to curved paths and to paths that have several
904 segments, as in the following examples:
905 %
906 \begin{codeexample}[]
907 \begin{tikzpicture}
908 \draw [<->] (0,0) arc [start angle=180, end angle=30, radius=10pt];
909 \draw [<->] (1,0) -- (1.5cm,10pt) -- (2cm,0pt) -- (2.5cm,10pt);
910 \end{tikzpicture}
911 \end{codeexample}
912
913 Karl has a more detailed look at the arrow that \tikzname\ puts at the end. It
914 looks like this when he zooms it: \tikz[baseline] \draw[->,line width=1pt]
915 (0pt,.5ex) -- ++(10pt,0pt);. The shape seems vaguely familiar and, indeed, this
916 is exactly the end of \TeX's standard arrow used in something like $f\colon A
917 \to B$.
918
919 Karl likes the arrow, especially since it is not ``as thick'' as the arrows
920 offered by many other packages. However, he expects that, sometimes, he might
921 need to use some other kinds of arrow. To do so, Karl can say |>=|\meta{kind of
922 end arrow tip}, where \meta{kind of end arrow tip} is a special arrow tip
923 specification. For example, if Karl says |>=Stealth|, then he tells \tikzname\
924 that he would like ``stealth-fighter-like'' arrow tips:
925 \todosp{remaining instance of bug \#473}
926 %
927 \begin{codeexample}[preamble={\usetikzlibrary{arrows.meta}}]
928 \begin{tikzpicture}[>=Stealth]
929 \draw [->] (0,0) arc [start angle=180, end angle=30, radius=10pt];
930 \draw [<<-,very thick] (1,0) -- (1.5cm,10pt) -- (2cm,0pt) -- (2.5cm,10pt);
931 \end{tikzpicture}
932 \end{codeexample}
933
934 Karl wonders whether such a military name for the arrow type is really
935 necessary. He is not really mollified when his son tells him that Microsoft's
936 PowerPoint uses the same name. He decides to have his students discuss this at
937 some point.
938
939 In addition to |Stealth| there are several other predefined kinds of arrow tips
940 Karl can choose from, see Section~\ref{section-arrows}. Furthermore, he can
941 define arrows types himself, if he needs new ones.
942
943
944 \subsection{Scoping}
945
946 Karl saw already that there are numerous graphic options that affect how paths
947 are rendered. Often, he would like to apply certain options to a whole set of
948 graphic commands. For example, Karl might wish to draw three paths using a
949 |thick| pen, but would like everything else to be drawn ``normally''.
950
951 If Karl wishes to set a certain graphic option for the whole picture, he can
952 simply pass this option to the |\tikz| command or to the |{tikzpicture}|
953 environment (Gerda would pass the options to |\tikzpicture| and Hans passes
954 them to |\starttikzpicture|). However, if Karl wants to apply graphic options
955 to a local group, he put these commands inside a |{scope}| environment (Gerda
956 uses |\scope| and |\endscope|, Hans uses |\startscope| and |\stopscope|). This
957 environment takes graphic options as an optional argument and these options
958 apply to everything inside the scope, but not to anything outside.
959
960 Here is an example:
961 %
962 \begin{codeexample}[]
963 \begin{tikzpicture}[ultra thick]
964 \draw (0,0) -- (0,1);
965 \begin{scope}[thin]
966 \draw (1,0) -- (1,1);
967 \draw (2,0) -- (2,1);
968 \end{scope}
969 \draw (3,0) -- (3,1);
970 \end{tikzpicture}
971 \end{codeexample}
972
973 Scoping has another interesting effect: Any changes to the clipping area are
974 local to the scope. Thus, if you say |\clip| somewhere inside a scope, the
975 effect of the |\clip| command ends at the end of the scope. This is useful
976 since there is no other way of ``enlarging'' the clipping area.
977
978 Karl has also already seen that giving options to commands like |\draw| apply
979 only to that command. It turns out that the situation is slightly more complex.
980 First, options to a command like |\draw| are not really options to the command,
981 but they are ``path options'' and can be given anywhere on the path. So,
982 instead of |\draw[thin] (0,0) -- (1,0);| one can also write
983 |\draw (0,0) [thin] -- (1,0);| or |\draw (0,0) -- (1,0) [thin];|; all of these
984 have the same effect. This might seem strange since in the last case, it would
985 appear that the |thin| should take effect only ``after'' the line from $(0,0)$
986 to $(1,0)$ has been drawn. However, most graphic options only apply to the
987 whole path. Indeed, if you say both |thin| and |thick| on the same path, the
988 last option given will ``win''.
989
990 When reading the above, Karl notices that only ``most'' graphic options apply
991 to the whole path. Indeed, all transformation options do \emph{not} apply to
992 the whole path, but only to ``everything following them on the path''. We will
993 have a more detailed look at this in a moment. Nevertheless, all options given
994 during a path construction apply only to this path.
995
996
997 \subsection{Transformations}
998
999 When you specify a coordinate like |(1cm,1cm)|, where is that coordinate
1000 placed on the page? To determine the position, \tikzname, \TeX, and
1001 \textsc{pdf} or PostScript all apply certain transformations to the given
1002 coordinate in order to determine the final position on the page.
1003
1004 \tikzname\ provides numerous options that allow you to transform coordinates in
1005 \tikzname's private coordinate system. For example, the |xshift| option allows
1006 you to shift all subsequent points by a certain amount:
1007
1008 \begin{codeexample}[]
1009 \tikz \draw (0,0) -- (0,0.5) [xshift=2pt] (0,0) -- (0,0.5);
1010 \end{codeexample}
1011
1012 It is important to note that you can change transformation ``in the middle of a
1013 path'', a feature that is not supported by \pdf\ or PostScript. The reason is
1014 that \tikzname\ keeps track of its own transformation matrix.
1015
1016 Here is a more complicated example:
1017 %
1018 \begin{codeexample}[]
1019 \begin{tikzpicture}[even odd rule,rounded corners=2pt,x=10pt,y=10pt]
1020 \filldraw[fill=yellow!80!black] (0,0) rectangle (1,1)
1021 [xshift=5pt,yshift=5pt] (0,0) rectangle (1,1)
1022 [rotate=30] (-1,-1) rectangle (2,2);
1023 \end{tikzpicture}
1024 \end{codeexample}
1025
1026 The most useful transformations are |xshift| and |yshift| for shifting, |shift|
1027 for shifting to a given point as in |shift={(1,0)}| or |shift={+(0,0)}| (the
1028 braces are necessary so that \TeX\ does not mistake the comma for separating
1029 options), |rotate| for rotating by a certain angle (there is also a
1030 |rotate around| for rotating around a given point), |scale| for scaling by a
1031 certain factor, |xscale| and |yscale| for scaling only in the $x$- or
1032 $y$-direction (|xscale=-1| is a flip), and |xslant| and |yslant| for slanting.
1033 If these transformation and those that I have not mentioned are not sufficient,
1034 the |cm| option allows you to apply an arbitrary transformation matrix. Karl's
1035 students, by the way, do not know what a transformation matrix is.
1036
1037
1038 \subsection{Repeating Things: For-Loops}
1039
1040 Karl's next aim is to add little ticks on the axes at positions $-1$, $-1/2$,
1041 $1/2$, and $1$. For this, it would be nice to use some kind of ``loop'',
1042 especially since he wishes to do the same thing at each of these positions.
1043 There are different packages for doing this. \LaTeX\ has its own internal
1044 command for this, |pstricks| comes along with the powerful |\multido| command.
1045 All of these can be used together with \tikzname, so if you are familiar with
1046 them, feel free to use them. \tikzname\ introduces yet another command, called
1047 |\foreach|, which I introduced since I could never remember the syntax of the
1048 other packages. |\foreach| is defined in the package |pgffor| and can be used
1049 independently of \tikzname, but \tikzname\ includes it automatically.
1050
1051 In its basic form, the |\foreach| command is easy to use:
1052 %
1053 \begin{codeexample}[]
1054 \foreach \x in {1,2,3} {$x =\x$, }
1055 \end{codeexample}
1056
1057 The general syntax is
1058 |\foreach| \meta{variable}| in {|\meta{list of values}|} |\meta{commands}.
1059 Inside the \meta{commands}, the \meta{variable} will be assigned to the
1060 different values. If the \meta{commands} do not start with a brace, everything
1061 up to the next semicolon is used as \meta{commands}.
1062
1063 For Karl and the ticks on the axes, he could use the following code:
1064 %
1065 \begin{codeexample}[]
1066 \begin{tikzpicture}[scale=3]
1067 \clip (-0.1,-0.2) rectangle (1.1,1.51);
1068 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
1069 \filldraw[fill=green!20,draw=green!50!black] (0,0) -- (3mm,0mm)
1070 arc [start angle=0, end angle=30, radius=3mm] -- cycle;
1071 \draw[->] (-1.5,0) -- (1.5,0);
1072 \draw[->] (0,-1.5) -- (0,1.5);
1073 \draw (0,0) circle [radius=1cm];
1074
1075 \foreach \x in {-1cm,-0.5cm,1cm}
1076 \draw (\x,-1pt) -- (\x,1pt);
1077 \foreach \y in {-1cm,-0.5cm,0.5cm,1cm}
1078 \draw (-1pt,\y) -- (1pt,\y);
1079 \end{tikzpicture}
1080 \end{codeexample}
1081
1082 As a matter of fact, there are many different ways of creating the ticks. For
1083 example, Karl could have put the |\draw ...;| inside curly braces. He could
1084 also have used, say,
1085 %
1086 \begin{codeexample}[code only]
1087 \foreach \x in {-1,-0.5,1}
1088 \draw[xshift=\x cm] (0pt,-1pt) -- (0pt,1pt);
1089 \end{codeexample}
1090
1091 Karl is curious what would happen in a more complicated situation where there
1092 are, say, 20 ticks. It seems bothersome to explicitly mention all these numbers
1093 in the set for |\foreach|. Indeed, it is possible to use |...| inside the
1094 |\foreach| statement to iterate over a large number of values (which must,
1095 however, be dimensionless real numbers) as in the following example:
1096 %
1097 \begin{codeexample}[]
1098 \tikz \foreach \x in {1,...,10}
1099 \draw (\x,0) circle (0.4cm);
1100 \end{codeexample}
1101
1102 If you provide \emph{two} numbers before the |...|, the |\foreach| statement
1103 will use their difference for the stepping:
1104 %
1105 \begin{codeexample}[]
1106 \tikz \foreach \x in {-1,-0.5,...,1}
1107 \draw (\x cm,-1pt) -- (\x cm,1pt);
1108 \end{codeexample}
1109
1110 We can also nest loops to create interesting effects:
1111 %
1112 \begin{codeexample}[]
1113 \begin{tikzpicture}
1114 \foreach \x in {1,2,...,5,7,8,...,12}
1115 \foreach \y in {1,...,5}
1116 {
1117 \draw (\x,\y) +(-.5,-.5) rectangle ++(.5,.5);
1118 \draw (\x,\y) node{\x,\y};
1119 }
1120 \end{tikzpicture}
1121 \end{codeexample}
1122
1123 The |\foreach| statement can do even trickier stuff, but the above gives the
1124 idea.
1125
1126
1127 \subsection{Adding Text}
1128
1129 Karl is, by now, quite satisfied with the picture. However, the most important
1130 parts, namely the labels, are still missing!
1131
1132 \tikzname\ offers an easy-to-use and powerful system for adding text and, more
1133 generally, complex shapes to a picture at specific positions. The basic idea is
1134 the following: When \tikzname\ is constructing a path and encounters the
1135 keyword |node| in the middle of a path, it reads a \emph{node specification}.
1136 The keyword |node| is typically followed by some options and then some text
1137 between curly braces. This text is put inside a normal \TeX\ box (if the node
1138 specification directly follows a coordinate, which is usually the case,
1139 \tikzname\ is able to perform some magic so that it is even possible to use
1140 verbatim text inside the boxes) and then placed at the current position, that
1141 is, at the last specified position (possibly shifted a bit, according to the
1142 given options). However, all nodes are drawn only after the path has been
1143 completely drawn/filled/shaded/clipped/whatever.
1144 %
1145 \begin{codeexample}[]
1146 \begin{tikzpicture}
1147 \draw (0,0) rectangle (2,2);
1148 \draw (0.5,0.5) node [fill=yellow!80!black]
1149 {Text at \verb!node 1!}
1150 -- (1.5,1.5) node {Text at \verb!node 2!};
1151 \end{tikzpicture}
1152 \end{codeexample}
1153
1154 Obviously, Karl would not only like to place nodes \emph{on} the last specified
1155 position, but also to the left or the right of these positions. For this, every
1156 node object that you put in your picture is equipped with several
1157 \emph{anchors}. For example, the |north| anchor is in the middle at the upper
1158 end of the shape, the |south| anchor is at the bottom and the |north east|
1159 anchor is in the upper right corner. When you give the option |anchor=north|,
1160 the text will be placed such that this northern anchor will lie on the current
1161 position and the text is, thus, below the current position. Karl uses this to
1162 draw the ticks as follows:
1163 %
1164 \begin{codeexample}[]
1165 \begin{tikzpicture}[scale=3]
1166 \clip (-0.6,-0.2) rectangle (0.6,1.51);
1167 \draw[step=.5cm,help lines] (-1.4,-1.4) grid (1.4,1.4);
1168 \filldraw[fill=green!20,draw=green!50!black] (0,0) -- (3mm,0mm)
1169 arc [start angle=0, end angle=30, radius=3mm] -- cycle;
1170 \draw[->] (-1.5,0) -- (1.5,0); \draw[->] (0,-1.5) -- (0,1.5);
1171 \draw (0,0) circle [radius=1cm];
1172
1173 \foreach \x in {-1,-0.5,1}
1174 \draw (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\x$};
1175 \foreach \y in {-1,-0.5,0.5,1}
1176 \draw (1pt,\y cm) -- (-1pt,\y cm) node[anchor=east] {$\y$};
1177 \end{tikzpicture}
1178 \end{codeexample}
1179
1180 This is quite nice, already. Using these anchors, Karl can now add most of the
1181 other text elements. However, Karl thinks that, though ``correct'', it is quite
1182 counter-intuitive that in order to place something \emph{below} a given point,
1183 he has to use the \emph{north} anchor. For this reason, there is an option
1184 called |below|, which does the same as |anchor=north|. Similarly, |above right|
1185 does the same as |anchor=south west|. In addition, |below| takes an optional
1186 dimension argument. If given, the shape will additionally be shifted downwards
1187 by the given amount. So, |below=1pt| can be used to put a text label below some
1188 point and, additionally shift it 1pt downwards.
1189
1190 Karl is not quite satisfied with the ticks. He would like to have $1/2$ or
1191 $\frac{1}{2}$ shown instead of $0.5$, partly to show off the nice capabilities
1192 of \TeX\ and \tikzname, partly because for positions like $1/3$ or $\pi$ it is
1193 certainly very much preferable to have the ``mathematical'' tick there instead
1194 of just the ``numeric'' tick. His students, on the other hand, prefer $0.5$
1195 over $1/2$ since they are not too fond of fractions in general.
1196
1197 Karl now faces a problem: For the |\foreach| statement, the position |\x|
1198 should still be given as |0.5| since \tikzname\ will not know where
1199 |\frac{1}{2}| is supposed to be. On the other hand, the typeset text should
1200 really be |\frac{1}{2}|. To solve this problem, |\foreach| offers a special
1201 syntax: Instead of having one variable |\x|, Karl can specify two (or even
1202 more) variables separated by a slash as in |\x / \xtext|. Then, the elements in
1203 the set over which |\foreach| iterates must also be of the form
1204 \meta{first}|/|\meta{second}. In each iteration, |\x| will be set to
1205 \meta{first} and |\xtext| will be set to \meta{second}. If no \meta{second} is
1206 given, the \meta{first} will be used again. So, here is the new code for the
1207 ticks:
1208 %
1209 \begin{codeexample}[]
1210 \begin{tikzpicture}[scale=3]
1211 \clip (-0.6,-0.2) rectangle (0.6,1.51);
1212 \draw[step=.5cm,help lines] (-1.4,-1.4) grid (1.4,1.4);
1213 \filldraw[fill=green!20,draw=green!50!black] (0,0) -- (3mm,0mm)
1214 arc [start angle=0, end angle=30, radius=3mm] -- cycle;
1215 \draw[->] (-1.5,0) -- (1.5,0); \draw[->] (0,-1.5) -- (0,1.5);
1216 \draw (0,0) circle [radius=1cm];
1217
1218 \foreach \x/\xtext in {-1, -0.5/-\frac{1}{2}, 1}
1219 \draw (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\xtext$};
1220 \foreach \y/\ytext in {-1, -0.5/-\frac{1}{2}, 0.5/\frac{1}{2}, 1}
1221 \draw (1pt,\y cm) -- (-1pt,\y cm) node[anchor=east] {$\ytext$};
1222 \end{tikzpicture}
1223 \end{codeexample}
1224
1225 Karl is quite pleased with the result, but his son points out that this is
1226 still not perfectly satisfactory: The grid and the circle interfere with the
1227 numbers and decrease their legibility. Karl is not very concerned by this (his
1228 students do not even notice), but his son insists that there is an easy
1229 solution: Karl can add the |[fill=white]| option to fill out the background of
1230 the text shape with a white color.
1231
1232 The next thing Karl wants to do is to add the labels like $\sin \alpha$. For
1233 this, he would like to place a label ``in the middle of the line''. To do so,
1234 instead of specifying the label |node {$\sin\alpha$}| directly after one of
1235 the endpoints of the line (which would place the label at that endpoint), Karl
1236 can give the label directly after the |--|, before the coordinate. By default,
1237 this places the label in the middle of the line, but the |pos=| options can be
1238 used to modify this. Also, options like |near start| and |near end| can be used
1239 to modify this position:
1240 %
1241 \begin{codeexample}[preamble={\usetikzlibrary{intersections}}]
1242 \begin{tikzpicture}[scale=3]
1243 \clip (-2,-0.2) rectangle (2,0.8);
1244 \draw[step=.5cm,gray,very thin] (-1.4,-1.4) grid (1.4,1.4);
1245 \filldraw[fill=green!20,draw=green!50!black] (0,0) -- (3mm,0mm)
1246 arc [start angle=0, end angle=30, radius=3mm] -- cycle;
1247 \draw[->] (-1.5,0) -- (1.5,0) coordinate (x axis);
1248 \draw[->] (0,-1.5) -- (0,1.5) coordinate (y axis);
1249 \draw (0,0) circle [radius=1cm];
1250
1251 \draw[very thick,red]
1252 (30:1cm) -- node[left=1pt,fill=white] {$\sin \alpha$} (30:1cm |- x axis);
1253 \draw[very thick,blue]
1254 (30:1cm |- x axis) -- node[below=2pt,fill=white] {$\cos \alpha$} (0,0);
1255 \path [name path=upward line] (1,0) -- (1,1);
1256 \path [name path=sloped line] (0,0) -- (30:1.5cm);
1257 \draw [name intersections={of=upward line and sloped line, by=t}]
1258 [very thick,orange] (1,0) -- node [right=1pt,fill=white]
1259 {$\displaystyle \tan \alpha \color{black}=
1260 \frac{{\color{red}\sin \alpha}}{\color{blue}\cos \alpha}$} (t);
1261
1262 \draw (0,0) -- (t);
1263
1264 \foreach \x/\xtext in {-1, -0.5/-\frac{1}{2}, 1}
1265 \draw (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north,fill=white] {$\xtext$};
1266 \foreach \y/\ytext in {-1, -0.5/-\frac{1}{2}, 0.5/\frac{1}{2}, 1}
1267 \draw (1pt,\y cm) -- (-1pt,\y cm) node[anchor=east,fill=white] {$\ytext$};
1268 \end{tikzpicture}
1269 \end{codeexample}
1270
1271 You can also position labels on curves and, by adding the |sloped| option, have
1272 them rotated such that they match the line's slope. Here is an example:
1273 %
1274 \begin{codeexample}[]
1275 \begin{tikzpicture}
1276 \draw (0,0) .. controls (6,1) and (9,1) ..
1277 node[near start,sloped,above] {near start}
1278 node {midway}
1279 node[very near end,sloped,below] {very near end} (12,0);
1280 \end{tikzpicture}
1281 \end{codeexample}
1282
1283 It remains to draw the explanatory text at the right of the picture. The main
1284 difficulty here lies in limiting the width of the text ``label'', which is
1285 quite long, so that line breaking is used. Fortunately, Karl can use the option
1286 |text width=6cm| to get the desired effect. So, here is the full code:
1287 %
1288 \begin{codeexample}[code only]
1289 \begin{tikzpicture}
1290 [scale=3,line cap=round,
1291 % Styles
1292 axes/.style=,
1293 important line/.style={very thick},
1294 information text/.style={rounded corners,fill=red!10,inner sep=1ex}]
1295
1296 % Colors
1297 \colorlet{anglecolor}{green!50!black}
1298 \colorlet{sincolor}{red}
1299 \colorlet{tancolor}{orange!80!black}
1300 \colorlet{coscolor}{blue}
1301
1302 % The graphic
1303 \draw[help lines,step=0.5cm] (-1.4,-1.4) grid (1.4,1.4);
1304
1305 \draw (0,0) circle [radius=1cm];
1306
1307 \begin{scope}[axes]
1308 \draw[->] (-1.5,0) -- (1.5,0) node[right] {$x$} coordinate(x axis);
1309 \draw[->] (0,-1.5) -- (0,1.5) node[above] {$y$} coordinate(y axis);
1310
1311 \foreach \x/\xtext in {-1, -.5/-\frac{1}{2}, 1}
1312 \draw[xshift=\x cm] (0pt,1pt) -- (0pt,-1pt) node[below,fill=white] {$\xtext$};
1313
1314 \foreach \y/\ytext in {-1, -.5/-\frac{1}{2}, .5/\frac{1}{2}, 1}
1315 \draw[yshift=\y cm] (1pt,0pt) -- (-1pt,0pt) node[left,fill=white] {$\ytext$};
1316 \end{scope}
1317
1318 \filldraw[fill=green!20,draw=anglecolor] (0,0) -- (3mm,0pt)
1319 arc [start angle=0, end angle=30, radius=3mm];
1320 \draw (15:2mm) node[anglecolor] {$\alpha$};
1321
1322 \draw[important line,sincolor]
1323 (30:1cm) -- node[left=1pt,fill=white] {$\sin \alpha$} (30:1cm |- x axis);
1324
1325 \draw[important line,coscolor]
1326 (30:1cm |- x axis) -- node[below=2pt,fill=white] {$\cos \alpha$} (0,0);
1327
1328 \path [name path=upward line] (1,0) -- (1,1);
1329 \path [name path=sloped line] (0,0) -- (30:1.5cm);
1330 \draw [name intersections={of=upward line and sloped line, by=t}]
1331 [very thick,orange] (1,0) -- node [right=1pt,fill=white]
1332 {$\displaystyle \tan \alpha \color{black}=
1333 \frac{{\color{red}\sin \alpha}}{\color{blue}\cos \alpha}$} (t);
1334
1335 \draw (0,0) -- (t);
1336
1337 \draw[xshift=1.85cm]
1338 node[right,text width=6cm,information text]
1339 {
1340 The {\color{anglecolor} angle $\alpha$} is $30^\circ$ in the
1341 example ($\pi/6$ in radians). The {\color{sincolor}sine of
1342 $\alpha$}, which is the height of the red line, is
1343 \[
1344 {\color{sincolor} \sin \alpha} = 1/2.
1345 \]
1346 By the Theorem of Pythagoras ...
1347 };
1348 \end{tikzpicture}
1349 \end{codeexample}
1350
1351
1352 \subsection{Pics: The Angle Revisited}
1353
1354 Karl expects that the code of certain parts of the picture he created might be
1355 so useful that he might wish to reuse them in the future. A natural thing to do
1356 is to create \TeX\ macros that store the code he wishes to reuse. However,
1357 \tikzname\ offers another way that is integrated directly into its parser:
1358 pics!
1359
1360 A ``pic'' is ``not quite a full picture'', hence the short name. The idea is
1361 that a pic is simply some code that you can add to a picture at different
1362 places using the |pic| command whose syntax is almost identical to the |node|
1363 command. The main difference is that instead of specifying some text in curly
1364 braces that should be shown, you specify the name of a predefined picture that
1365 should be shown.
1366
1367 Defining new pics is easy enough, see Section~\ref{section-pics}, but right now
1368 we just want to use one such predefined pic: the |angle| pic. As the name
1369 suggests, it is a small drawing of an angle consisting of a little wedge and an
1370 arc together with some text (Karl needs to load the |angles| library and the
1371 |quotes| for the following examples). What makes this pic useful is the fact
1372 that the size of the wedge will be computed automatically.
1373
1374 The |angle| pic draws an angle between the two lines $BA$ and $BC$, where $A$,
1375 $B$, and $C$ are three coordinates. In our case, $B$ is the origin, $A$ is
1376 somewhere on the $x$-axis and $C$ is somewhere on a line at $30^\circ$.
1377 %
1378 \begin{codeexample}[preamble={\usetikzlibrary{angles,quotes}}]
1379 \begin{tikzpicture}[scale=3]
1380 \coordinate (A) at (1,0);
1381 \coordinate (B) at (0,0);
1382 \coordinate (C) at (30:1cm);
1383
1384 \draw (A) -- (B) -- (C)
1385 pic [draw=green!50!black, fill=green!20, angle radius=9mm,
1386 "$\alpha$"] {angle = A--B--C};
1387 \end{tikzpicture}
1388 \end{codeexample}
1389
1390 Let us see, what is happening here. First we have specified three
1391 \emph{coordinates} using the |\coordinate| command. It allows us to name a
1392 specific coordinate in the picture. Then comes something that starts as a
1393 normal |\draw|, but then comes the |pic| command. This command gets lots of
1394 options and, in curly braces, comes the most important point: We specify that
1395 we want to add an |angle| pic and this angle should be between the points we
1396 named |A|, |B|, and |C| (we could use other names). Note that the text that we
1397 want to be shown in the pic is specified in quotes inside the options of the
1398 |pic|, not inside the curly braces.
1399
1400 To learn more about pics, please see Section~\ref{section-pics}.