Reader small image

You're reading from  LaTeX Graphics with TikZ

Product typeBook
Published inJun 2023
PublisherPackt
ISBN-139781804618233
Edition1st Edition
Tools
Right arrow
Author (1)
Stefan Kottwitz
Stefan Kottwitz
author image
Stefan Kottwitz

Stefan Kottwitz studied mathematics in Jena and Hamburg. He works as a network and IT security engineer both for Lufthansa Industry Solutions and for Eurowings Aviation. For many years, he has been providing LaTeX support on online forums. He maintains the web forums LaTeX and goLaTeX and the Q&A sites TeXwelt and TeXnique. He runs the TeX graphics gallery sites TeXample, TikZ, and PGFplots, the TeXlive online compiler, the TeXdoc service, and the CTAN software mirror. He is a moderator of the TeX Stack Exchange site and matheplanet. He publishes ideas and news from the TeX world on his blogs LaTeX and TeX. Before this book, he authored the first edition of LaTeX Beginner's Guide in 2011, and LaTeX Cookbook in 2015, both published by Packt.
Read more about Stefan Kottwitz

Right arrow

Calculating with
Coordinates and Paths

In Chapter 1, Creating the First TikZ Images, we started off using explicit values to choose coordinates. We achieved relative positioning by manually giving distances while drawing a path.

Now, we are about to take things to the next level by introducing a whole new set of techniques for calculating coordinates from other coordinates. We can add or subtract coordinates from each other, calculate a coordinate position between other coordinates at a certain distance, find a coordinate as a projection onto a line, and rotate coordinates.

And that’s not all – we’ll introduce loop commands that help repeat calculations and actions.

Get ready to dive deep into the following techniques:

  • Repeating in loops
  • Calculating with coordinates
  • Evaluating loop variables
  • Calculating intersections of paths

By the end of this chapter, you will be ultra-efficient in repeating similar commands and using calculations...

Technical requirements

The source code of the chapter’s examples is available at https://tikz.org/chapter-10. The code can be downloaded from GitHub at https://github.com/PacktPublishing/LaTeX-graphics-with-TikZ/tree/main/10-calculating-transforming.

In this chapter, we will use the calc and intersections TikZ libraries; other features are loaded by default.

Repeating in loops

The easiest calculation is counting, so this will be our starting point. In a for loop, TikZ can count with a variable for us while it repeats a code segment using the variable. While this sounds simple, it’s tremendously valuable for generating graphics with ease, especially with the TikZ \foreach command, which is incredibly flexible.

The basic syntax of this command is the following:

\foreach variable in {list of values} {commands};

Let’s break down the highlighted code:

  • variable: We name and use it like a macro, such as \i. The convention of using i as a loop variable dates back to the early programming languages and mathematics, when x and y were used for variables and i and j were used as indexing counters. However, we are free to choose any name as long as it starts with a backslash.
  • list of values: This is a comma-separated list of values, such as 1,2,3. You can omit values and write – for example, 1,...,10 –...

Calculating with coordinates

The calc library allows us basic operations with coordinates. Load it first in the document preamble with \usetikzlibrary{calc}, and you’re ready to go.

TikZ can now calculate what we write between $ symbols within a coordinate. While it may look like TeX inline math mode, it actually enables us to perform calculations and math operations.

Adding and subtracting coordinates

With just the simple notation of $(A)+(B)$ we can add two coordinates. How can this be useful? It’s an easy relative positioning when we use a particular coordinate and add a coordinate to have a shift in the x and y directions.

Let’s start with a coordinate, A, at some arbitrary position and build what we can see in Figure 10.5:

\coordinate (A) at (1,2);

Now, we can create a coordinate that’s just right of it, with an x distance of 1, by adding a coordinate with suitable values, x=1 and y=0:

\coordinate (B) at ($(A)+(1,0)$);

Note that...

Evaluating loop variables

Let’s take a closer look at the code for Figure 10.8. Could there possibly be even more variable options to adjust? How about iterating colors and interconnecting between loop repetitions? Yes, you can achieve this within the same loop. So, let’s look at further advanced \foreach options – at first, some syntax with short examples, and then a more extended example.

Counting loop repetitions

A \foreach value list can contain alphanumeric values and patterns to be iterated through and utilized within the loop commands. However, we may want to use values based on their position in the list, such as using the (\j,0) coordinate at position j in the iterative order of list values.

This is where the count option comes into play. Let’s say we have \i as the loop variable iterating through letters. We introduce the \j counter as follows:

\foreach \i [count=\j] in {A,...,Z} {commands};

Now, while \i iterates from A to Z, \j...

Calculating intersections of paths

TikZ drawings are often built step by step. We choose coordinates and draw lines, curves, and shapes. At some point, we may need to know the intersection of such paths to proceed with further drawing steps, such as adding text or arrows at such positions.

We could calculate the intersection point of two lines ourselves by solving a system of two linear equations. To get the intersection points of a circle and a line, we can solve a quadratic equation. Remember polygons or shapes consisting of curvy paths such as bent lines? It can become hard to compute a point on such a path that overlaps with another path.

TikZ provides the intersections library that solves such challenges. You can load it in the usual way:

\usetikzlibrary{intersections}

Now, TikZ can do all the hard work and calculate all intersection points of arbitrary paths, generating named coordinates for them.

Let’s dive into a basic example to see how it works. We&...

Summary

You saw that TikZ’s loops are incredibly flexible. You can use loops whenever you see stuff repeating and want to save yourself from writing repetitive code.

Calculating with coordinates can now make your life easier. Just add a coordinate to move in the x or y direction or with an angle or distance. Use factors to place something in between nodes or coordinates. That’s not just for geometry; this handy syntax is helpful for any lines, arrows, or positioning nodes in complex diagrams in a perfectly controlled manner.

Letting TikZ calculate intersection points of lines, curves, and complex paths helps you create more intricate shapes based on simpler ones.

In the next chapter, you will learn how to transform coordinates, paths, and scopes, such as by transposition and rotation.

Further reading

The following sections in the TikZ manual at https://texdoc.org/pkg/tikz are the reference for the commands, syntax, and libraries used in this chapter:

  • Part VII, Section 88, Repeating Things: The Foreach Statement, gives all formal details of the \foreach command and its syntax. You can also find it at https://tikz.dev/pgffor.
  • Part III, Section 13.5, Coordinate Calculations, is the reference for the calc library. The direct online link is https://tikz.dev/tikz-coordinates#sec-13.5.
  • Part III, Section 13.3, Coordinates at Intersections, explains working with path intersections and is available online at https://tikz.dev/tikz-coordinates#sec-13.3.

As you already know, the TikZ galleries contain many examples relevant to this chapter. You can visit the following:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
LaTeX Graphics with TikZ
Published in: Jun 2023Publisher: PacktISBN-13: 9781804618233
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Stefan Kottwitz

Stefan Kottwitz studied mathematics in Jena and Hamburg. He works as a network and IT security engineer both for Lufthansa Industry Solutions and for Eurowings Aviation. For many years, he has been providing LaTeX support on online forums. He maintains the web forums LaTeX and goLaTeX and the Q&A sites TeXwelt and TeXnique. He runs the TeX graphics gallery sites TeXample, TikZ, and PGFplots, the TeXlive online compiler, the TeXdoc service, and the CTAN software mirror. He is a moderator of the TeX Stack Exchange site and matheplanet. He publishes ideas and news from the TeX world on his blogs LaTeX and TeX. Before this book, he authored the first edition of LaTeX Beginner's Guide in 2011, and LaTeX Cookbook in 2015, both published by Packt.
Read more about Stefan Kottwitz