# 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]:

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

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

Out[3]:

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

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

Out[4]:

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 [5]:
a.ylabelStyle = "rotate = -90"
a.legendStyle = "{at={(1.05,1.0)},anchor=north west}"
a

Out[5]:

This will remove the latest added setting

In [6]:
popPGFPlotsOptions();


And to reset all options, use

In [7]:
resetPGFPlotsOptions();


You can set the width and height of the axis.

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

Out[8]:

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 [9]: Axis(Plots.Linear(x, y), xlabel=L"$X$", ylabel=L"$Y$", title=L"$\int_0^\infty e^{\pi x}dx$")  Out[9]: 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 [10]: Plots.Linear(x->sqrt(2*x) + sin(x), (0,10), xbins=51)  Out[10]: You can put multiple plots on the same axis and assign legend entries. In [11]: Axis([ Plots.Linear(sin, (0,10), legendentry=L"$\sin(x)$"), Plots.Linear(x->sqrt(2*x), (0,10), legendentry=L"$\sqrt{2x}$") ])  Out[11]: You can change the legend position by setting the legendPos parameter in the axis. In [12]: 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[12]: 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 [13]: Plots.Linear(1:10, sin.(1:10), style="ycomb")  Out[13]: You can also do horizontal comb plots. In [14]: Plots.Linear(abs.(sin.(1:10)), 1:10, style="xcomb")  Out[14]: You can also make it smooth. In [15]: Plots.Linear(1:10, sin.(1:10), style="smooth")  Out[15]: There is support for constant plots. In [16]: Plots.Linear(1:10, sin.(1:10), style="const plot")  Out[16]: In [17]: Plots.Linear(1:10, sin.(1:10), style="ybar")  Out[17]: In [18]: Plots.Linear(1:10, sin.(1:10), style="ybar,fill=green", mark="none")  Out[18]: You can give an axis a log scale by specifying xmode or ymode parameters of Axis: In [19]: p = Plots.Linear(0.01:0.01:1, 10 .^(0.01:0.01:1), mark="none") Axis(p, ymode="log")  Out[19]: Fill and fill opacity can be handled through the style parameter. In [20]: p = Plots.Linear(0:10, (0:10).^2, style="red, fill=blue, fill opacity=0.3", mark="none")  Out[20]: 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 [21]: p = Plots.Linear(0:10, 2*(0:10)) a = Axis(p, axisEqual=true, xmin=0, xmax=10) # note xmin and xmax are disregarded...  Out[21]: 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 [22]: p = Plots.Linear(0:10, 2*(0:10)) a = Axis(p, axisEqualImage=true)  Out[22]: You can change the size of the markers with the markSize argument. The default marker size is 2. In [23]: Plots.Linear(0:10, 2*(0:10), markSize=10)  Out[23]: To eliminate the line and only use marks, you can set the onlyMarks argument to true. In [24]: Plots.Linear(0:10, 2*(0:10), onlyMarks=true)  Out[24]: ### Error Bars¶ You can plot error bars for Linear and Scatter plots. Here we specify an array for the y error. In [25]: x = [1,2,3] y = [2,4,1] plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5]))  Out[25]: The y error does not have to be symmetric. In [26]: plot(x, y, errorBars = ErrorBars(yplus=[1, 0.3, 0.5], yminus=[0.5, 0.1, 0.1]))  Out[26]: You can also specify x error. In [27]: plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5], x=[0.1, 0.1, 0.05]))  Out[27]: You can change the style. In [28]: plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5], style="red,very thick"))  Out[28]: You can also specify the mark. In [29]: plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5], mark="diamond"))  Out[29]: You can control the style of the plot line along with the error bars. In [30]: plot(x, y, style="red", errorBars = ErrorBars(y=[1, 0.3, 0.5], style="black,very thick", mark="diamond"))  Out[30]: ### 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 [31]: x = 1:10 y = 2x Plots.Scatter(x, y)  Out[31]: 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 [32]: z = 3x Plots.Scatter(x, y, z)  Out[32]: To add a colorbar, you can set the colorbar argument to true. In [33]: p = Plots.Scatter(x, y, z) a = Axis(p, colorbar=true)  Out[33]: 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 [34]: 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[34]: You can add a legend using the legendentry keyword. In [35]: Plots.Scatter(x, y, z, scatterClasses=sc, legendentry=["A", "B", "C"])  Out[35]: You can customize the legend using optionsto the Axis (since the legend style is a property of the Axis). In [36]: Axis(Plots.Scatter(x, y, z, scatterClasses=sc, legendentry=["A", "B", "C"]), style="legend columns=-1", legendPos="north west")  Out[36]: ### 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 [37]: d = randn(100) Axis(Plots.Histogram(d, bins=10), ymin=0)  Out[37]: You can even create a cumulative distribution function from the data. In [38]: Axis(Plots.Histogram(d, bins=20, cumulative=true, density=true), ymin=0)  Out[38]: 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 [39]: Axis(Plots.Histogram(d, bins=10, style="red,fill=red!10"), ymin=0, ylabel="Counts")  Out[39]: 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 [40]: Axis(Plots.Histogram(d, discretization=:auto), ymin=0)  Out[40]: Several discretization algorithms are provided by Discretizers.jl. In [41]: 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[41]: ### Bar Charts¶ Bar charts differ from histograms in that they represent values assigned to distinct items. A BarChart has keys and values. In [42]: Plots.BarChart(["a", "b"], [1,2])  Out[42]: If only values are passed in, the keys will be set to the first$n\$ integers.

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

Out[43]:

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

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

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

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

Out[46]:

### Images¶

Image plots create a PNG bitmap and can be used to visualize functions. The second and third arguments below are tuples specifying the x and y ranges.

In [47]:
f = (x,y)->x*exp(-x^2-y^2)
Plots.Image(f, (-2,2), (-2,2))

Out[47]:

You can set the zmin and zmax. By default, it uses the minimum and maximum values of the data.

In [48]:
Plots.Image(f, (-2,2), (-2,2), zmin=-1, zmax=1)

Out[48]:

You can invert the Gray colormap.

In [49]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.GrayMap(invert = true))

Out[49]: