Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
LaTeX Graphics with TikZ

You're reading from  LaTeX Graphics with TikZ

Product type Book
Published in Jun 2023
Publisher Packt
ISBN-13 9781804618233
Pages 304 pages
Edition 1st Edition
Languages
Author (1):
Stefan Kottwitz Stefan Kottwitz
Profile icon Stefan Kottwitz

Table of Contents (18) Chapters

Preface 1. Chapter 1: Getting Started with TikZ 2. Chapter 2: Creating the First TikZ Images 3. Chapter 3: Drawing and Positioning Nodes 4. Chapter 4: Drawing Edges and Arrows 5. Chapter 5: Using Styles and Pics 6. Chapter 6: Drawing Trees and Graphs 7. Chapter 7: Filling, Clipping, and Shading 8. Chapter 8: Decorating Paths 9. Chapter 9: Using Layers, Overlays, and Transparency 10. Chapter 10: Calculating with Coordinates and Paths 11. Chapter 11: Transforming Coordinates and Canvas 12. Chapter 12: Drawing Smooth Curves 13. Chapter 13: Plotting in 2D and 3D 14. Chapter 14: Drawing Diagrams 15. Chapter 15: Having Fun with TikZ 16. Index 17. Other Books You May Enjoy

Plotting in 2D and 3D

Whether you’re a scientist, analyst, engineer, teacher, or student, you know that proper visualization is vital to understanding your data.

If you decide to showcase your data using diagrams such as line charts, bar charts, or pie charts, then Chapter 14, Drawing Diagrams, will cover you.

If you want to visualize your data in a coordinate system in LaTeX, then the current chapter is the right place.

In this chapter, we’ll be covering the following topics:

  • Introducing plotting
  • Creating and customizing Cartesian axes, ticks, and labels
  • Using plotting commands and options
  • Filling the area between plots
  • Calculating plot intersections
  • Adding a legend
  • Using the polar coordinate system
  • Parametric plotting
  • Plotting in three dimensions

After studying this chapter, you will be able to easily plot datasets and mathematical functions in a scientific and technical context.

Technical requirements

This chapter’s examples are at https://tikz.org/chapter-13. On GitHub, they are at https://github.com/PacktPublishing/LaTeX-graphics-with-TikZ/tree/main/13-plotting.

The pgfplots package is crucial here and must be installed in your LaTeX distribution. pgfplots is built on the pgf/TikZ packages, so you must have it installed and loaded in your document. If you don’t load pgf/TikZ explicitly, pgfplots will load it automatically. If you use TikZ.org, Overleaf, or TeXlive.net, pgfplots is already included. We will also use the pgfplots libraries colormaps, fillbetween, and polar, which are bundled with pgfplots.

Introducing plotting

Let’s begin by discussing and briefly assessing the available options for plotting, both in the commercial software market and the open source community.

Several commercial software options are available, such as Mathematica and Matlab, as well as free and open source software such as GNU Octave, R, GNUplot, and Python with Matplotlib, for example. Any of these programs can be used to generate plots and export them as images for inclusion in your LaTeX document. However, there are some drawbacks to using third-party software:

  • You need to install and maintain another software installation, you may have to pay for installation and updates, and you will be dependent on the software’s functionality on a specific computer.
  • Imported images may appear blurry or pixelated if exported in bitmap formats such as PNG or JPG. If possible, export them as PDF images to obtain a scalable image.
  • Font types and the sizes of labels and numbers may...

Creating and customizing Cartesian axes, ticks, and labels

In Chapter 12, Drawing Smooth Curves, we identified and plotted a few points with self-made axes and a grid. We will plot them now using pgfplots to get a first glance at the syntax.

Take a look at this code, which you can download from GitHub or the Chapter 13 page on TikZ.org:

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
  \begin{axis}[grid]
    \addplot[only marks] coordinates
      { (-3,-2.4)  (-2,0.4) (-0.4,0.4)
        (0.4,-0.4) (2,-0.4) (3,2.4) };
  \end{axis}
\end{tikzpicture}
\end{document}

By compiling this document, we get the following output:

Figure 13.1 – Plotting coordinates

Figure 13.1 – Plotting coordinates

At first, we load the pgfplots package and set version 1.18 for compatibility. As pgfplots uses TikZ, every...

Using plotting commands and options

We already encountered the most important command, which is \addplot. You may have noticed that when we used \addplot with options, the color of the plot was black. When we did not use options, it was blue.

The reason is that a so-called cycle list contains the color and marker style for plots. So, by default, the first plot in a drawing would be blue, the second would be red, and the third would be green color. We leave the details of this to the pgfplots manual so we understand how the coloring happens.

So, when we use \addplot[color=yellow, ...], the options provided will replace the default options.

The \addplot+ command, however, appends the given options to the default options. We won’t use it here, but it’s good to know for when you see it used online and when you want to use the pre-defined cycle list of blue, red, and green for the first three plots in a diagram.

For both commands, we have three variants:

    ...

Filling the area between plots

In Chapter 7, Filling, Clipping, and Shading, we dealt with filling areas enclosed by TikZ paths. Now we will do the same with plots.

You may remember the integral of a function over an interval: it represents the exact area between the curve and the x-axis over the interval. Let’s see how to visualize this.

The fillbetween library provides ways to fill areas between plots and axes. You can load it this way:

\usepgfplotslibrary{fillbetween}

Let’s look at the axes and how we can access them as TikZ paths. pgfplots has its own coordinate system that can be accessed using the axis cs prefix. Using this, the plot coordinate system coordinates are translated to TikZ coordinates. So, in TikZ, we can work with a coordinate (axis cs:1,2) which is the coordinate (1,2) in the plot coordinate system, no matter what its TikZ size is.

In the following example, we give a plot a path name. Then, we define a TikZ path with axis cs coordinates...

Calculating plot intersections

In Chapter 10, Calculating with Coordinates and Paths, we calculated the intersection points of TikZ paths. Similarly, we can let pgfplots determine the intersections of plots. If you use the fillbetween library as we did in the previous section, pgfplots will automatically load the TikZ intersections library. Otherwise, you can load it yourself.

First, we need to give each plot path a name. Then, we can calculate the intersection points as we did in Chapter 10, highlighted here:

\begin{axis}[axis lines = center, axis equal,
    domain = -1.5:1]
  \addplot[name path=cubic]   {x^3/5 - x};
  \addplot[name path=quartic] {(x^2-1)^2};
  \fill[name intersections = {of=cubic and quartic,
   name=p}]
    (p-1) circle (2pt) node [above right] {$p_1$}
    (p-2) circle (2pt) node [left]        {$p_2...

Adding a legend

When we have several plots or datasets, it can help to identify each plot with a different color and a description. To do this, we can add a legend. Typically, this is a box within the plot area containing a symbol or color to identify each plot, along with their descriptions.

To the code of the previous example, we just need to add the following axis option:

legend entries = {$\frac{1}{5}x^3-x$, $(x^2-1)^2$}

This adds a box with a description of our plot:

Figure 13.9 – Plots with a legend

Figure 13.9 – Plots with a legend

To place the legend in the top left of the plot, add legend pos = north west to the axis options. Similarly, you can choose south west or south east, whereas north east is the default. If you don’t have any whitespace where the legend fits nicely, you can set legend pos = outer north east; then, the legend will be placed next to the top-right corner of the plot without overlapping. You can see this in Figure 14.13.

The legend...

Using the polar coordinate system

In Chapter 2, we talked about polar coordinates. Polar coordinates are just perfect for representing circular or radial symmetric data. Have a quick look back at that chapter, especially at Figure 2.5.

To use polar coordinates, we need to load the corresponding library:

\usepgfplotslibrary{polar}

Then, we have a new polaraxis environment. We can use this just like a normal axis, except that the labels, ticks, and grids are now radial. Take a look at this:

\begin{polaraxis}
  \addplot[domain=0:180, samples=100, thick] {sin(3*x)};
\end{polaraxis}

While a polar plot of sin(x) would give us a simple circle, this relatively simple plot command provides us with the following plot with three leaves:

Figure 13.10 – A trigonometric function in a polar coordinate system

Figure 13.10 – A trigonometric function in a polar coordinate system

We can drive it on and use a large domain, especially with a fractional argument of the sine function, like this:

\addplot[domain...

Parametric plotting

In Chapter 10, we used the calc package to draw Archimedean spirals in Figure 10.8 and Figure 10.9. The syntax gets easier with a plotting package, and we get a coordinate system with axes on top.

Instead of using degrees for angles, we can use radians. These are an alternative means of angle measurement, happily used especially by mathematicians. Though radian values are simple numbers, we usually express them in multiples of π. For example, a right angle, 90 degrees, would be written as π/2, and 180 degrees are equal to π. We could say 180 degrees is about 3.14 in radians, but we use π. In the same way, 360 degrees equal 2π, and 1,080 degrees is 6π.

We will use radian values and labels in our next plot. For this, we switch the plotting format to radian using the following command:

\pgfplotsset{trig format plots=rad}

Now, we can use radian values for the domain of the plot, which is calculated with radian arguments...

Plotting in three dimensions

pgfplots has impressive 3D plotting capabilities. There are so many customization options that we will leave most of the details to the manual and just go through a few examples here.

We will use the \addplot3 command similarly to \addplot; now, we have functions such as z = f(x,y) or parametrization in x, y, and z.

pgfplots easily provides 3D axes, drawn as a box with ticks at the edges by default. One interesting feature is color maps: we can improve our 3D visualizations by mapping the z value to a color. To get started, let’s load the corresponding library first:

\usepgfplotslibrary{colormaps}

We continue to use the radian format:

\pgfplotsset{trig format plots=rad}

We will use a black-and-white color map, where the lowest z values are black, and the higher the z value, the lighter the color. The highest z value will be printed in white.

A typical visualization is a surface plot that draws a mesh representing the function...

Summary

In this chapter, you gained knowledge and skills to visualize data points and mathematical functions in scientific or technical presentations. You can now plot datasets and functions in both two and three dimensions with Cartesian or polar coordinates to present your data in an informative and pleasing way.

The next chapter will teach you to present data using diagrams and charts.

Further reading

The TikZ manual at https://texdoc.org/pkg/tikz explains basic plotting in Part III, Section 22, Plots of Functions. You can read it online at https://tikz.dev/tikz-plots.

Part VI, Data Visualization, covers data point and function plots in depth on more than a hundred pages. This is a new and promising concept; you may consider it as a fresh alternative to pgfplots. The quick link is https://tikz.dev/dv.

The pgfplots package is comprehensively documented in its detailed manual. This excellent reference document contains numerous examples and even tutorials. You can open it at the command line with texdoc pgfplots or visit https://texdoc.org/pkg/pgfplots.

Did you like the tikz.dev deep links to particular sections in past chapters? Then you may appreciate this: while I was writing this book, the pgfplots manual was also made available as an online HTML version. You can browse it at https://tikz.dev/pgfplots.

The LaTeX Cookbook from Packt Publishing, written...

lock icon The rest of the chapter is locked
You have been reading a chapter from
LaTeX Graphics with TikZ
Published in: Jun 2023 Publisher: Packt ISBN-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.
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}