# PGFPlots¶

This library uses the LaTeX package pgfplots to produce plots. It integrates with IJulia, outputting SVG images to the notebook. This version of PGFPlots requires Julia 0.6 or later.

## Installation¶

Pkg.add("PGFPlots")

In addition, you will need to install the following dependencies if you do not already have them on your system.

• Pdf2svg. This is required by TikzPictures. On Ubuntu, you can get this by running sudo apt-get install pdf2svg and on RHEL/Fedora by running sudo dnf install pdf2svg. On Windows, you can download the binaries from http://www.cityinthesky.co.uk/opensource/pdf2svg/. Be sure to add pdf2svg to your path (and restart).
• Pgfplots (version 1.10 or later). Install using your latex package manager (e.g., texlive or miktex).

Once these things are installed, you should be able to run the following:

In [1]:
using PGFPlots


## Examples¶

### Linear Plots¶

You can create a very basic plot by passing in vectors of $x$ and $y$ coordinates.

In [2]:
x = [1,2,3]
y = [2,4,1]
plot(x, y)

Out[2]:

You can also inspect the tikz code that is generated for any plot.

Note that you can also store plots directly as .tex files instead of inspecting their code as Strings (see Saving below)

In [3]:
print(tikzCode(x, y))

\begin{axis}

(1, 2)
(2, 4)
(3, 1)
};

\end{axis}

The version of the plot function above actually just creates an empty Axis and inserts a Plots.Linear instance containing the data.

In [4]:
Axis(Plots.Linear(x, y))

Out[4]:

If you create the Axis object explicitly, as done above, then you can set various properties of the axis.

In [5]:
pushPGFPlotsOptions("scale=1.5")
a = Axis(Plots.Linear(x, y, legendentry="My Plot"), xlabel="X", ylabel="Y", title="My Title")

Out[5]:

The options can be set after the plot a is created. Here we rotate the y-label and move the legend by setting the ylabelStyle and legendStyle:

In [6]:
a.ylabelStyle = "rotate = -90"
a.legendStyle = "at={(1.05,1.0)}, anchor=north west"
a

Out[6]:
In [7]:
print(tikzCode(a))

\begin{axis}[
legend style = {at={(1.05,1.0)}, anchor=north west},
ylabel = {Y},
ylabel style = {rotate = -90},
title = {My Title},
xlabel = {X}
]

(1, 2)
(2, 4)
(3, 1)
};

\end{axis}

This will remove the latest added setting

In [8]:
popPGFPlotsOptions();


And to reset all options, use

In [9]:
resetPGFPlotsOptions();


You can set the width and height of the axis.

In [10]:
Axis(Plots.Linear(x, y), width="3cm", height="3cm")

Out[10]:

Since latex is used to typeset everything, you can use any latex math symbols you want. If you use L"..." (as below), you do not have to escape \ and $. In [11]: Axis(Plots.Linear(x, y), xlabel=L"$X$", ylabel=L"$Y$", title=L"$\int_0^\infty e^{\pi x}dx$")  Out[11]: It is possible to pass a dictionary with arbitrary options to the axis with the customOptions keyword: You can pass in a function and its domain. It will automatically be evaluated based on the provided domain atxbins evenly-spaced points. In [12]: Plots.Linear(x->sqrt(2*x) + sin(x), (0,10), xbins=51)  Out[12]: You can put multiple plots on the same axis and assign legend entries. In [13]: Axis([ Plots.Linear(sin, (0,10), legendentry=L"\sin(x)"), Plots.Linear(x->sqrt(2*x), (0,10), legendentry=L"\sqrt{2x}") ])  Out[13]: You can change the legend position by setting the legendPos parameter in the axis. In [14]: Axis([ Plots.Linear(sin, (0,10), legendentry=L"\sin(x)"), Plots.Linear(x->sqrt(2*x), (0,10), legendentry=L"\sqrt{2x}") ], legendPos="north west")  Out[14]: Not all entries need to have legends. The "forget plot" option can be used to skip a plot. Note that "forget plot" does not advance the cycle list color. In [15]: Axis([ Plots.Linear(sin, (0,10), style="red", legendentry=L"\sin(x)"), Plots.Linear(x->sqrt(2*x), (0,10), style="blue, forget plot"), Plots.Linear(x->3exp(-x), (0,10), style="green", legendentry=L"3 \exp{-x}") ])  Out[15]: You can do comb plots by setting the style. The style string gets passed directly into PGFPlots, giving you full control over the plots (see PGFPlots documentation). In [16]: Plots.Linear(1:10, sin.(1:10), style="ycomb")  Out[16]: You can also do horizontal comb plots. In [17]: Plots.Linear(abs.(sin.(1:10)), 1:10, style="xcomb")  Out[17]: You can also make it smooth. In [18]: Plots.Linear(1:10, sin.(1:10), style="smooth")  Out[18]: There is support for constant plots. In [19]: Plots.Linear(1:10, sin.(1:10), style="const plot")  Out[19]: In [20]: Plots.Linear(1:10, sin.(1:10), style="ybar")  Out[20]: In [21]: Plots.Linear(1:10, sin.(1:10), style="ybar,fill=green", mark="none")  Out[21]: You can give an axis a log scale by specifying xmode or ymode parameters of Axis: In [22]: p = Plots.Linear(0.01:0.01:1, 10 .^(0.01:0.01:1), mark="none") Axis(p, ymode="log")  Out[22]: Fill and fill opacity can be handled through the style parameter. In [23]: p = Plots.Linear(0:10, (0:10).^2, style="red, fill=blue, fill opacity=0.3", mark="none")  Out[23]: If you want the tick marks to be equal, you can set axisEqual to true (equivalent to axis equal in LaTeX). Note that this will also change the limit sizes, over riding xmax, xmin, ymin, and ymax. In [24]: p = Plots.Linear(0:10, 2*(0:10)) Axis(p, axisEqual=true, xmin=0, xmax=10) # note xmin and xmax are disregarded...  Out[24]: If this flippant disregard of your axis limit authority displeases you, you can set axisEqualImage to true (equivalent to axis equal image). This will leave the limits alone, and let you modify them. In [25]: p = Plots.Linear(0:10, 2*(0:10)) Axis(p, axisEqualImage=true)  Out[25]: You can change the size of the markers with the markSize argument. The default marker size is 2. In [26]: Plots.Linear(0:10, 2*(0:10), markSize=10)  Out[26]: To eliminate the line and only use marks, you can set the onlyMarks argument to true. In [27]: Plots.Linear(0:10, 2*(0:10), onlyMarks=true)  Out[27]: ### Discrete Linear¶ We can associate values with an integer range, which defaults to starting at 1, and produce a piecewise constant plot. In [28]: Plots.DiscreteLinear([3,1,4,1,5,9,2,6,5])  Out[28]: We can start at integer values other than 1 by using the start keyword. We can also adjust the style of the plot. In [29]: Plots.DiscreteLinear([3,1,4,1,5,9,2,6,5]; start=0, style="no marks")  Out[29]: ### Stacked Plots¶ Here are a couple plots before they are stacked. In [30]: Axis([ Plots.Linear(x->sin(x), (0,2)), Plots.Linear(x->abs(1.5*sin(2x)^2), (0,2)) ])  Out[30]: We can stack plots by setting the appropriate style. In [31]: Axis([ Plots.Linear(x->sin(x), (0,2)), Plots.Linear(x->abs(1.5*sin(2x)^2), (0,2)) ], style="stack plots=y")  Out[31]: We can create area plots like this. In [32]: Axis([ Plots.Linear(x->sin(x), (0,2), closedCycle=true), Plots.Linear(x->abs(1.5*sin(2x)^2), (0,2), closedCycle=true) ], style="stack plots=y, area style, enlarge x limits=false", ymin=0)  Out[32]: ### Error Bars¶ You can plot error bars for Linear and Scatter plots. Here we specify an array for the y error. In [33]: x = [1,2,3] y = [2,4,1] plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5]))  Out[33]: The y error does not have to be symmetric. In [34]: plot(x, y, errorBars = ErrorBars(yplus=[1, 0.3, 0.5], yminus=[0.5, 0.1, 0.1]))  Out[34]: You can also specify x error. In [35]: plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5], x=[0.1, 0.1, 0.05]))  Out[35]: You can change the style. In [36]: plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5], style="red,very thick"))  Out[36]: You can also specify the mark. In [37]: plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5], mark="diamond"))  Out[37]: You can control the style of the plot line along with the error bars. In [38]: plot(x, y, style="red", errorBars = ErrorBars(y=[1, 0.3, 0.5], style="black,very thick", mark="diamond"))  Out[38]: ### Scatter Plots¶ A simple scatter plot is just a linear plot with "only marks". The following code returns a Linear plot with "only marks" selected: In [39]: x = 1:10 y = 2x Plots.Scatter(x, y)  Out[39]: PGFPlots gives you the option of picking a color for each scatter point. You can provide a third vector with the desired color values. The following code returns a Scatter plot where points with smaller z-values are blue. Points redden as the z-values increase. In [40]: z = 3x Plots.Scatter(x, y, z)  Out[40]: To add a colorbar, you can set the colorbar argument to true. In [41]: p = Plots.Scatter(x, y, z) a = Axis(p, colorbar=true)  Out[41]: In [42]: print(tikzCode(a))  \begin{axis}[ colorbar = {true} ] \addplot+[ scatter, scatter src = explicit, only marks = {true} ] coordinates { (1, 2) [3] (2, 4) [6] (3, 6) [9] (4, 8) [12] (5, 10) [15] (6, 12) [18] (7, 14) [21] (8, 16) [24] (9, 18) [27] (10, 20) [30] }; \end{axis} If you want non-numeric data to determine the coloration and marking of each scatter point, you must provide the scatterClasses argument and describe what each symbol means. This is the same string that would be passed into the tex file if you were writing it yourself. The following code colors points by their class ("a", "b", or "c"). In [43]: z = ["a", "a", "a", "b", "b", "b", "b", "c", "c", "c"] sc = "a={mark=square,blue}, b={mark=triangle,red}, c={mark=o,black}" Plots.Scatter(x, y, z, scatterClasses=sc)  Out[43]: You can add a legend using the legendentry keyword. In [44]: Plots.Scatter(x, y, z, scatterClasses=sc, legendentry=["A", "B", "C"])  Out[44]: You can customize the legend using optionsto the Axis (since the legend style is a property of the Axis). In [45]: Axis(Plots.Scatter(x, y, z, scatterClasses=sc, legendentry=["A", "B", "C"]), style="legend columns = -1", legendPos="north west")  Out[45]: ### Histograms¶ It is very easy to make histograms. It is just another type under the Plots module. You should be able to use autocompletion in your editor (e.g., IJulia) to see what Plots are supported. In [46]: d = randn(100) a = Axis(Plots.Histogram(d, bins=10), ymin=0)  Out[46]: In [47]: print(tikzCode(a))  \begin{axis}[ ymin = {0} ] \addplot+[ mark = none, fill=blue!10, hist = {density = {false}, cumulative = {false}, bins = {10}} ] table[ row sep=\\, y index = 0 ] { data \\ 1.2786097960454506 \\ 0.27455371656010114 \\ 0.6139826707312067 \\ -0.40199689487253165 \\ 0.05580321322879142 \\ 0.11484583637194319 \\ -1.3427227423992825 \\ 0.5267216893164791 \\ -0.8000511860076166 \\ -0.3741688224277814 \\ 0.8222867330867403 \\ 0.34401223623160604 \\ -0.48544760334720877 \\ 0.8247522112983386 \\ -0.5157259550079027 \\ -1.8370271764530701 \\ -0.6761265339890828 \\ -1.2383639378234128 \\ 1.1989843376284437 \\ 1.4947994820758903 \\ 0.049516934361568926 \\ 1.3881833166307678 \\ -0.4520155651901849 \\ 1.2616193299302076 \\ -0.7437593448973283 \\ 1.5414843739586739 \\ 2.0457818836829924 \\ -0.4400801576506409 \\ -0.7458300844270593 \\ 0.7490313155948072 \\ -0.31586593194771156 \\ 1.5301040179124195 \\ 0.9134961256392568 \\ 0.06592568520139298 \\ -1.4139744506177396 \\ -0.26702103833489843 \\ 0.7210842772203139 \\ -2.040778372477219 \\ 2.6304152705393973 \\ 0.4851176533454339 \\ -0.8650331937339066 \\ 0.5805379306358163 \\ -0.3115796246800618 \\ 0.7982191661964226 \\ 0.8184615427569875 \\ 0.6664055372420544 \\ 1.6945879637868926 \\ -0.5019889863557239 \\ 0.3399260133998397 \\ 0.8112784643725501 \\ 0.27910773980232023 \\ 0.5481144845189347 \\ 0.3998177007166334 \\ -1.3177636830916821 \\ -0.7912474823565749 \\ -2.0866917907003395 \\ -1.4818851305968503 \\ 0.25107381862970224 \\ -0.007200671855892979 \\ -2.0986456166562366 \\ -1.624298234602372 \\ -1.3724128178361672 \\ -0.22089134429549254 \\ -0.7502226774123257 \\ 0.05630074553506217 \\ 0.8783591170525625 \\ 0.48912651365268384 \\ -0.4142311427180589 \\ 0.8270757536326449 \\ 1.2364384098135277 \\ -0.761650701205329 \\ -2.24934923801777 \\ -1.834199661770146 \\ -1.3810972207194363 \\ 0.1758323701265651 \\ 1.3490129309169727 \\ -1.5248438694411268 \\ -0.7889598447128455 \\ 1.792633030013226 \\ 0.3088887023886808 \\ -0.6754080498406553 \\ 0.10587703615531457 \\ -0.5826442306676526 \\ 0.4598580667119365 \\ 0.8958647348873555 \\ -0.9158100054987125 \\ 0.5813973709293011 \\ 0.748705696131095 \\ -2.0205374393675184 \\ 0.575433590933501 \\ 0.1498403499714464 \\ -0.7655568462349297 \\ 1.1651323668915603 \\ 0.9741647095700178 \\ 2.0223731960610247 \\ -0.8414969221090633 \\ -0.2700935539594514 \\ -0.5313691940647755 \\ -1.590826296624782 \\ 0.4785345776778956 \\ }; \end{axis} You can even create a cumulative distribution function from the data. In [48]: Axis(Plots.Histogram(d, bins=20, cumulative=true, density=true), ymin=0)  Out[48]: As with the other plots, you can control the style. The documentation on tikz and pgfplots can give you more information about what styles are supported. In [49]: Axis(Plots.Histogram(d, bins=10, style="red, fill=red!10"), ymin=0, ylabel="Counts")  Out[49]: Sometimes you do not want to store your raw dataset in a Tikz file, especially when the dataset is large. The discretization option lets you specify what discretization algorithm to use. In [50]: Axis(Plots.Histogram(d, discretization=:auto), ymin=0)  Out[50]: Several discretization algorithms are provided by Discretizers.jl. In [51]: using Random discretizations = [:default, # use PGFPlots for small data sizes and :auto for large :pgfplots, # use the PGFPlots histogram function (uses nbins, which defaults to 10) :specified, # use Discretizers.jl but with the specified number of bins (which defaults to 10) :auto, # max between :fd and :sturges. Good all-round performance :fd, # Freedman Diaconis Estimator, robust :sturges, # R's default method, only good for near-Gaussian data :sqrt, # used by Excel and others for its simplicity and speed :doane, # improves Sturgesâ€™ for non-normal datasets. :scott, # less robust estimator that that takes into account data variability and data size. ] Random.seed!(0) data = [randn(500).*1.8 .+ -5; randn(2000).*0.8 .+ -4; randn(500).*0.3 .+ -1; randn(1000).*0.8 .+ 2; randn(500).*1.5 .+ 4; ] data = filter!(x->-15.0 <= x <= 15.0, data) g = GroupPlot(3, 3, groupStyle = "horizontal sep = 1.75cm, vertical sep = 1.5cm") for discretization in discretizations push!(g, Axis(Plots.Histogram(data, discretization=discretization), ymin=0, title=string(discretization))) end g  Out[51]: ### Bar Charts¶ Bar charts differ from histograms in that they represent values assigned to distinct items. A BarChart has keys and values. In [52]: p = Plots.BarChart(["a", "b"], [1,2])  Out[52]: In [53]: print(tikzCode(p))  \begin{axis}[ ybar = 0pt, bar width = 18pt, xtick = data, symbolic x coords = {a, b}, ymin = {0} ] \addplot+ coordinates { (a, 1) (b, 2) }; \end{axis} If only values are passed in, the keys will be set to the first$n\$ integers.

In [54]:
Plots.BarChart([3,4,5,2,10])

Out[54]:

Vectors of AbstractStrings will be counted and the strings used as keys.

In [55]:
Plots.BarChart(["cat", "dog", "cat", "cat", "dog", "mouse"])

Out[55]:
In [56]:
Plots.BarChart([L"x", L"x^2", L"x^2", L"sin(x)", "hello world"])

Out[56]:
In [57]:
Axis(Plots.BarChart(["potayto", "potahto", "tomayto", "tomahto"], [1,2,3,4], style="cyan"),
xlabel="vegetables", ylabel="counts", style="bar width=25pt")

Out[57]: