PG F Plot Basics

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

pgfplots generates beautiful simple graphs

Tony Roberts

May 23, 2016

For research, lecture notes, tutorials, examinations, and online quizzes we


often need to simply generate high quality graphs. The LATEX package
pgfplots does a beautiful and flexible job such as the following. This document
concisely summarises some useful basics of 2D pgfplots (3D is available but
not addressed here).
4 y
f
g
f ◦g
2

x
−4 −2 2 4

−2

−4

Contents
1 Basic figure template 2

1
1 Basic figure template 2

2 Graph formulas 2

3 Options 4

4 Extras 6

5 Further examples 7

1 Basic figure template

Invoke with \usepackage{pgfplots} in any regular LATEX document. I


prefer to first draft a graph interactively using the application LaTeXiT. The
general format for drawing a figure (often within a center environment) is
for a single curve use
\begin{tikzpicture}
\begin{axis}[axis-options]
\addplot formula;
\end{axis}
\end{tikzpicture}
for multiple curves use
\begin{tikzpicture}
\begin{axis}[axis-options]
\addplot[plot-options] formula;
\addlegendentry{label}
\addplot[plot-options] formula;
\addlegendentry{label}
...
\end{axis}
\end{tikzpicture}

Tony Roberts, May 23, 2016


2 Graph formulas 3

2 Graph formulas

function plot To plot a curve where the vertical coordinate is a function


of the horizontal coordinate, just give the function formula in terms
of x within braces. For example
\addplot {-4+x^2-x^4/32};
Trigonometric functions assume degrees, so invoke as sin(deg(x)) for
example, and convert arc-functions as in atan(x)/deg(1).
parametric plot For a parametric plot give the horizontal and vertical
formulas in terms of ‘x’ within braces,
√ comma separated, within paren-
theses. For example, to plot y = 2x − 4 one could do
\addplot ({x^2/2+2},{x});
given data In place of formula, use coordinates{point-list} where the
point-list has the form (x1,y1)(x2,y2)...(xn,yn) for the numerical
data point coordinates (no commas between the parentheses). For
example, to draw the absolute value function one could
\addplot coordinates{(-2,2)(0,0)(2,2)}
Legend? specify \addlegendentry{...} immediately after the curve plot.
Annotation? specifying \node at (axis cs:x1,y1) {text}; after an
\addplot ...; annotates a plot with the text centered at the location
(x1,y1) in the plot coordinate system.

For example the following draws the figure shown at the start of this
document, and using some of the options explained next.
\begin{tikzpicture}
\begin{axis}[ xlabel={$x$}, ylabel={$y$}
,axis lines=middle
,samples=41 , grid , thick
,domain=-4:4
,legend pos=outer north east

Tony Roberts, May 23, 2016


3 Options 4

]
\addplot[blue,no marks] {-4+x^2-x^4/32};
\addlegendentry{$f$}
\addplot[red,no marks] {13/4-(x+1)^2/4};
\addlegendentry{$g$}
\addplot[brown,mark=*,mark repeat=5]
{-4+(13/4-(x+1)^2/4)^2-(13/4-(x+1)^2/4)^4/32};
\addlegendentry{$f\circ g$}
\end{axis}
\end{tikzpicture}

3 Options

The options for the axis-options and the plot-options are largely the same:
it is just that the plot-options override corresponding attributes set in the
axis-options.
Multiple options need to be comma separated, and may span many lines.
All options are optional, but some are usual.
• axis lines=middle pgfplot graphics normally are boxed, but for
many purposes we want axes through the origin, so often invoke this.
• xlabel={$x$} defines horizontal axis label.
• ylabel={$y$} defines vertical axis label; sometimes useful for la-
belling the plotted function as in ylabel={$y=\sin x$}.
• title={...} defines a title to go across the top of the plot when
necessary.
• samples=41 The pgfplot default is to use a distressingly few points
to approximate a curve; overriding it, to say 41, is usual.
• smooth Draws a smooth curve between data points (is an alternative
to samples), especially useful for plots from specified coordinate points.

Tony Roberts, May 23, 2016


3 Options 5

• thick specifies the curves are drawn a bit thicker, which usually
seems good to do.
• grid for some plots we want a grid drawn.
• legend pos=... specifies the position of the legend in a multi-curve
figure: can be one of outer north east (safely outside the plotted
area), north east, south east, north west, south west.
• domain=a:b usually desirable and specifies the domain [a, b] for the
variable x in the formula; if not a parametric plot, then this will also
be the horizontal extent of the plot.
• xmin=a, xmax=b, ymin=c, ymax=d specifies the horizontal and ver-
tical domains of the plot; any curve or data point outside these ranges
are clipped out of the plot; needed sometimes.
• colour? To specify colour just write the corresponding word from blue,
red, brown, green, cyan, magenta, yellow, black, gray, white,
darkgray, lightgray, lime, olive, orange, pink, purple, teal,
violet.
• dashed plots the curve dashed; there is also solid, dotted, dashdotted
and dashdotdotted.
• no marks the default is to mark every ‘data point’ (even if a formulaic
curve); usually omit such marks.
Whereas only marks omits the line joining the data points.
• mark=... to override the default mark; choose from * (discs), x, +,
or more with \usetikzlibrary{plotmarks}.
• mark repeat=n instead of marking every data point, this marks every
nth data point (starting with the first); sometimes useful with specified
number of samples.
• axis equal image make the axes of equal scaling, and trim width
or height to suit.

Tony Roberts, May 23, 2016


4 Extras 6

• small, footnotesize use one of these to make the figure smaller,


or even smaller still, respectively. You may also want to include
font=\small or font=\footnotesize to correspondingly change the
size of any annotations.
• ybar interval,black,fill=pink will form a (vertical) bar plot
with black rectangles and filled with pink. Similarly for xbar interval.
• xtick={-2,...,8} will force x-axis labels and grids to be drawn at
every integer between −2 and 8. Whereas xtick={a,c,...,b} puts
x-axis labels and grids at a : δ : b where δ = c − a. Analogously for
ytick.
• xticklabels={list} will label each x-axis tick with specified infor-
mation. For example, xtick={1,3,4} and xticklabels={$a$,$x$,$b$}
specifies three ticks at these locations but labels them a, x and b re-
spectively. Analogously for yticklabels.

4 Extras

• \pgfplotsset{options} Sets global options so they do not have to


be repeated. For example, make all plots small by \pgfplotsset{small}.
• rand generates a random number for each invocation in a function at
each data point; the random numbers are uniform over [−1, 1].
• Inequalities provide the step function: for example, (x>0.5) is the
function which is zero for x ≤ 0.5 and one for x > 0.5 .
• \node[pin=45:{$e$}] at (axis cs:2.71828,0) {}; Put after an
\addplot ...; annotates a plot with a pin and a marker at the given
location.
\node[circle,fill=blue,scale=0.5,pin=135:{$(3,24)$}] at (axis cs
additionally draws a circular marker there as well.
• You can mix colours: for example, teal!50!white gives a pale teal.

Tony Roberts, May 23, 2016


5 Further examples 7

• Option opacity=fraction makes something somewhat transparent; for


example, fill opacity=0.5 makes a fill 50% transparent.
• \addplot[...] {...} \closedcycle; is useful for shading regions
as it draws end-lines and fills-in down to the horizontal axis.
• hide y axis does precisely what it says.
• One can add explanatory text to a legend with
\addlegendimage{empty legend}
\addlegendentry[text width=9em,text depth=]{The quick
brown fox jumps over the lazy dog.}
It is typeset ragged-right.
• Drawing the graphs is computationally expensive: if it gets too slow
you can get them drawn to a pdf file once and then seamlessly read
back in thereafter. Be careful: graphs are not redrawn until you specify.
– Invoke this drawing to file by placing in the preamble
\usepgfplotslibrary{external}
\tikzexternalize
– \tikzsetnextfilename{filename} It seems best to identify
precisely what the pdf file is to be called so invoke this command
immediately before every \begin{tikzpicture}. The filename
can include folder hierarchy.
– \tikzset{external/force remake} then forces a redraw of all
the pgfplots if necessary or when desirable.

5 Further examples

Christian Feuersanger provides many examples, including these.

Tony Roberts, May 23, 2016


5 Further examples 8

Basic Plot

3 Case 1
Case 2

2
y label

0
0 1 2 3
x axis

1 \begin{tikzpicture}
2 \begin{axis}[axis equal, title={\textbf{Basic Plot}},
3 xlabel={$x$ axis}, ylabel={$y$ label}]
4 \addplot+[smooth,mark=*] plot coordinates
5 { (0,2) (2,3) (3,1) };
6 \addlegendentry{Case 1}
7 \addplot+[smooth,mark=x] plot coordinates
8 { (0,0) (1,1) (2,1) (3,2) };
9 \addlegendentry{Case 2}
10 \end{axis}
11 \end{tikzpicture}

Tony Roberts, May 23, 2016


5 Further examples 9

Log-log Plot

10−1 d=2
d=3
10−2 d=4
d=5
L2 Error

d=6
10−3

10−4
dy
dx = −1.58
10−5

101 102 103 104 105 106


Dof

1 \begin{tikzpicture}
2 \begin{loglogaxis}[title={\textbf{Log-log Plot}},
3 xlabel=\textsc{Dof}, ylabel={$L_2$ Error} ]
4 \axispath\draw
5 (7.49165,-10.02171)
6 |- (8.31801,-11.32467)
7 node[near start,left] {$\frac{dy}{dx} = -1.58$};
8 \addplot plot coordinates {
9 (5, 8.312e-02)
10 (17, 2.547e-02)
11 (49, 7.407e-03)
12 (129, 2.102e-03)
13 (321, 5.874e-04)
14 (769, 1.623e-04)
15 (1793, 4.442e-05)
16 (4097, 1.207e-05)
17 (9217, 3.261e-06) };
18 \addplot plot coordinates {

Tony Roberts, May 23, 2016


5 Further examples 10

19 (7, 8.472e-02)
20 (31, 3.044e-02)
21 (111, 1.022e-02)
22 (351, 3.303e-03)
23 (1023, 1.039e-03)
24 (2815, 3.196e-04)
25 (7423, 9.658e-05)
26 (18943, 2.873e-05)
27 (47103, 8.437e-06) };
28 \addplot plot coordinates {
29 (9, 7.881e-02)
30 (49, 3.243e-02)
31 (209, 1.232e-02)
32 (769, 4.454e-03)
33 (2561, 1.551e-03)
34 (7937, 5.236e-04)
35 (23297, 1.723e-04)
36 (65537, 5.545e-05)
37 (178177, 1.751e-05) };
38 \addplot plot coordinates {
39 (11, 6.887e-02)
40 (71, 3.177e-02)
41 (351, 1.341e-02)
42 (1471, 5.334e-03)
43 (5503, 2.027e-03)
44 (18943, 7.415e-04)
45 (61183, 2.628e-04)
46 (187903, 9.063e-05)
47 (553983, 3.053e-05) };
48 \addplot plot coordinates {
49 (13, 5.755e-02)
50 (97, 2.925e-02)
51 (545, 1.351e-02)
52 (2561, 5.842e-03)
53 (10625, 2.397e-03)

Tony Roberts, May 23, 2016


5 Further examples 11

54 (40193, 9.414e-04)
55 (141569, 3.564e-04)
56 (471041, 1.308e-04)
57 (1496065, 4.670e-05) };
58 \legend{$d=2$\\$d=3$\\$d=4$\\$d=5$\\$d=6$\\}
59 \end{loglogaxis}
60 \end{tikzpicture}
Surface plot

−1
0 200
100
200
300 0

1 \begin{tikzpicture}
2 \begin{axis}[title={\textbf{Surface plot}}]
3 \addplot3[surf,domain=0:360,samples=40]
4 {sin(x)*sin(y)};
5 \end{axis}
6 \end{tikzpicture}

Tony Roberts, May 23, 2016

You might also like