Plots

Options

Plotting is NOT a builtin feature of julia. You can choose from several different options:

  • PyPlot
  • PlotlyJS
  • PGFPlots
  • UnicodePlots
  • Gadlfy
  • ...

Every package has different goals and pros / cons.

PyPlot

Matlab - esque syntax

PlotlyJS

interactive plots

Gadfly

R - esque syntax

PGFPlots

nice plots, uses pgfplots lates package

UnicodePlots

nice if the command line is all you have / want

Meta - Approach: Plots Package

  • provides unified syntax for a few plotting packages.
  • plotting backend can be switched on the fly
  • accessing underlying plotting backend can be accessed
  • does not support all available plotting packages for julia

In [6]:
Pkg.add("Plots")
Pkg.add("PyPlot")
Pkg.add("GR")
Pkg.add("UnicodePlots")
Pkg.add("PlotlyJS")


INFO: Package Plots is already installed
INFO: Cloning cache of Conda from https://github.com/JuliaPy/Conda.jl.git
INFO: Cloning cache of LaTeXStrings from https://github.com/stevengj/LaTeXStrings.jl.git
INFO: Cloning cache of MacroTools from https://github.com/MikeInnes/MacroTools.jl.git
INFO: Cloning cache of PyCall from https://github.com/JuliaPy/PyCall.jl.git
INFO: Cloning cache of PyPlot from https://github.com/JuliaPy/PyPlot.jl.git
INFO: Installing Conda v0.7.0
INFO: Installing LaTeXStrings v0.2.1
INFO: Installing MacroTools v0.3.7
INFO: Installing PyCall v1.15.0
INFO: Installing PyPlot v2.3.2
INFO: Building Conda
INFO: Building PyCall
INFO: PyCall is using python (Python 2.7.12) at /usr/bin/python, libpython = libpython2.7
INFO: /home/juser/.julia/v0.6/PyCall/deps/deps.jl has been updated
INFO: /home/juser/.julia/v0.6/PyCall/deps/PYTHON has been updated
INFO: Package database updated
INFO: Cloning cache of GR from https://github.com/jheinen/GR.jl.git
INFO: Installing GR v0.23.0
INFO: Building GR
INFO: Downloading pre-compiled GR 0.26.0 Ubuntu binary
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 38.3M  100 38.3M    0     0  7867k      0  0:00:04  0:00:04 --:--:-- 9928k
INFO: Package database updated
INFO: Cloning cache of UnicodePlots from https://github.com/Evizero/UnicodePlots.jl.git
INFO: Installing UnicodePlots v0.2.5
INFO: Building SpecialFunctions
INFO: Package database updated
INFO: Cloning cache of Blink from https://github.com/JunoLab/Blink.jl.git
INFO: Cloning cache of DocStringExtensions from https://github.com/JuliaDocs/DocStringExtensions.jl.git
INFO: Cloning cache of Hiccup from https://github.com/JunoLab/Hiccup.jl.git
INFO: Cloning cache of HttpServer from https://github.com/JuliaWeb/HttpServer.jl.git
INFO: Cloning cache of Juno from https://github.com/JunoLab/Juno.jl.git
INFO: Cloning cache of Lazy from https://github.com/MikeInnes/Lazy.jl.git
INFO: Cloning cache of Media from https://github.com/JunoLab/Media.jl.git
INFO: Cloning cache of Mustache from https://github.com/jverzani/Mustache.jl.git
INFO: Cloning cache of Mux from https://github.com/JuliaWeb/Mux.jl.git
INFO: Cloning cache of PlotlyJS from https://github.com/sglyon/PlotlyJS.jl.git
INFO: Cloning cache of WebSockets from https://github.com/JuliaWeb/WebSockets.jl.git
INFO: Installing Blink v0.5.3
INFO: Installing DocStringExtensions v0.4.0
INFO: Installing Hiccup v0.1.1
INFO: Installing HttpServer v0.2.0
INFO: Installing Juno v0.3.1
INFO: Installing Lazy v0.11.7
INFO: Installing Media v0.3.0
INFO: Installing Mustache v0.3.0
INFO: Installing Mux v0.2.3
INFO: Installing PlotlyJS v0.6.4
INFO: Installing WebSockets v0.2.3
INFO: Building HttpParser
INFO: Building MbedTLS
INFO: Building SpecialFunctions
INFO: Building PlotlyJS
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  864k    0  864k    0     0   494k      0 --:--:--  0:00:01 --:--:--  494k
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 2243k  100 2243k    0     0  4423k      0 --:--:-- --:--:-- --:--:-- 4424k

WARNING: deprecated syntax "_ as an rvalue around /home/juser/.julia/v0.6/PlotlyJS/deps/make_schema_docs.jl:22".
INFO: Package database updated

In [1]:
using Plots

In [2]:
plotly(); x = 1:0.1:10; plot(sin,x)


Out[2]:

In [3]:
gr(); x = 1:0.1:10; plot(sin,x)


Out[3]:
2 4 6 8 10 -0.75 -0.50 -0.25 0.00 0.25 0.50 0.75 y1

In [4]:
pyplot(); x = 1:0.1:10; plot(sin,x)


Out[4]:

In [48]:
using DataFrames

In [53]:
slideData = readtable("slideTimes.csv",separator=';');

In [60]:



Out[60]:
4 5 6 7 0 5 10 15 20 y1

In [56]:
bar(slideData[:time],nbins=10)


Out[56]:
0 25 50 75 100 0 2 4 6 y1

Basic Plot Types

Parametric


In [5]:
plotly(); plot(sin, cos, -pi, pi,aspect_ratio=1)


Out[5]:

Scatter


In [6]:
scatter(rand(100),rand(100))


Out[6]:

Bar


In [7]:
bar(rand(100))


Out[7]:

Histogram


In [8]:
histogram(rand(100),nbins=10)


Out[8]:

In [9]:
histogram2d(rand(1000),rand(1000),nbins=10)


WARNING: Keyword argument match_dimensions not supported with Plots.PlotlyBackend().  Choose from: Set(Symbol[:yticks, :zforeground_color_guide, :top_margin, :lims, :group, :zguidefont, :foreground_color_border, :inset_subplots, :background_color, :xscale, :marker_z, :yforeground_color_text, :markerstrokealpha, :left_margin, :markeralpha, :xguidefont, :annotations, :window_title, :zrotation, :seriesalpha, :foreground_color_axis, :zlink, :ygridlinewidth, :seriescolor, :smooth, :zscale, :xrotation, :xticks, :y, :tickfont, :xgrid, :margin, :foreground_color_title, :bottom_margin, :title_location, :ygridalpha, :yforeground_color_border, :zlims, :colorbar, :zdiscrete_values, :zflip, :zgridalpha, :ticks, :scale, :linealpha, :background_color_legend, :linecolor, :html_output_format, :zforeground_color_border, :normalize, :linestyle, :foreground_color_legend, :title, :subplot_index, :xflip, :ytickfont, :yforeground_color_guide, :zgrid, :fillcolor, :flip, :ygrid, :bar_width, :background_color_inside, :z, :bins, :markerstrokestyle, :foreground_color_grid, :yforeground_color_axis, :zforeground_color_text, :zguide, :yscale, :weights, :xtickfont, :xgridalpha, :linewidth, :clims, :fill_z, :xguide, :markershape, :background_color_subplot, :gridalpha, :fillalpha, :markerstrokewidth, :xerror, :gridlinewidth, :foreground_color_subplot, :ylims, :xgridlinewidth, :hover, :foreground_color, :ztickfont, :primary, :foreground_color_text, :x, :yerror, :rotation, :zgridlinewidth, :yguidefont, :legend, :discrete_values, :aspect_ratio, :xforeground_color_text, :foreground_color_guide, :grid, :show, :link, :ribbon, :colorbar_title, :xforeground_color_axis, :xforeground_color_guide, :xdiscrete_values, :legendfont, :background_color_outside, :subplot, :guidefont, :label, :size, :orientation, :guide, :projection, :markersize, :ydiscrete_values, :xforeground_color_grid, :yguide, :seriestype, :yflip, :quiver, :zticks, :markerstrokecolor, :fillrange, :titlefont, :zforeground_color_axis, :zforeground_color_grid, :layout, :polar, :right_margin, :xforeground_color_border, :markercolor, :xlims, :series_annotations, :yrotation, :xlink, :ylink, :levels, :color_palette, :yforeground_color_grid])
Out[9]:

In [42]:
using DataFrames

In [43]:
studentData = readtable("HomeworkVSexamClean.csv",separator=';');

In [44]:
describe(studentData)


homework
Summary Stats:
Mean:           34.332770
Minimum:        0.000000
1st Quartile:   28.000000
Median:         41.000000
3rd Quartile:   46.000000
Maximum:        51.000000
Length:         592
Type:           Int64
Number Missing: 0
% Missing:      0.000000

exam
Summary Stats:
Mean:           3.806419
Minimum:        1.000000
1st Quartile:   3.300000
Median:         4.000000
3rd Quartile:   4.700000
Maximum:        5.000000
Length:         592
Type:           Float64
Number Missing: 0
% Missing:      0.000000


In [45]:
histogram2d(studentData[:homework],studentData[:exam],nbins=10)


WARNING: Keyword argument match_dimensions not supported with Plots.GRBackend().  Choose from: Set(Symbol[:yticks, :zguidefont, :top_margin, :lims, :group, :zgridstyle, :foreground_color_border, :inset_subplots, :background_color, :xscale, :marker_z, :yforeground_color_text, :markerstrokealpha, :left_margin, :markeralpha, :xguidefont, :annotations, :window_title, :seriesalpha, :foreground_color_axis, :zlink, :ygridlinewidth, :seriescolor, :smooth, :zscale, :xticks, :y, :tickfont, :xgrid, :margin, :ygridalpha, :bottom_margin, :zdiscrete_values, :yforeground_color_border, :zlims, :colorbar, :framestyle, :zflip, :ticks, :zgridalpha, :scale, :linealpha, :background_color_legend, :linecolor, :overwrite_figure, :arrow, :normalize, :linestyle, :html_output_format, :zforeground_color_border, :foreground_color_legend, :title, :subplot_index, :xflip, :ytickfont, :zgrid, :fillcolor, :flip, :ygrid, :bar_width, :background_color_inside, :z, :bins, :yforeground_color_axis, :foreground_color_grid, :zforeground_color_text, :zguide, :yscale, :weights, :xtickfont, :xgridalpha, :ygridstyle, :linewidth, :xguide, :markershape, :background_color_subplot, :gridalpha, :fillalpha, :markerstrokewidth, :xerror, :gridlinewidth, :foreground_color_subplot, :ylims, :xgridlinewidth, :foreground_color, :ztickfont, :primary, :foreground_color_text, :x, :yerror, :zgridlinewidth, :yguidefont, :legend, :discrete_values, :aspect_ratio, :xforeground_color_text, :grid, :show, :link, :ribbon, :xforeground_color_axis, :xdiscrete_values, :legendfont, :background_color_outside, :legendtitle, :subplot, :guidefont, :label, :xgridstyle, :size, :orientation, :guide, :gridstyle, :markersize, :projection, :ydiscrete_values, :xforeground_color_grid, :yguide, :seriestype, :yflip, :quiver, :zticks, :markerstrokecolor, :fillrange, :zforeground_color_axis, :zforeground_color_grid, :layout, :polar, :right_margin, :xforeground_color_border, :markercolor, :xlims, :series_annotations, :xlink, :ylink, :levels, :color_palette, :yforeground_color_grid])
Out[45]:
0 10 20 30 40 50 1 2 3 4 5 0 10 20 30 40 50 60

In [47]:
histogram2d(studentData[:homework],studentData[:exam],nbins=10,yflip=true)


Out[47]:
0 10 20 30 40 50 1 2 3 4 5 0 10 20 30 40 50 60

Pie


In [13]:
pie(["Sugar","Flour","Egg","Love"],[1,2,0.5,1])


Out[13]:

Contour


In [14]:
contour(-10:10,-10:10, (x,y) -> exp(Complex(x,y))/Complex(x,y)^10 |> abs |> log10)


Out[14]:

In [15]:
contour(-10:10,-10:10, (x,y) -> exp(Complex(x,y))/Complex(x,y)^10 |> abs |> log10,fill=true)


Out[15]:

In [125]:
using SpecialFunctions

In [16]:
contour(-10:10,-10:10, (x,y) -> airyai(x + y*im)/(x+y*im)^10 |> abs |> log10,fill=true)


Out[16]:

In [17]:
contour(-10:0.1:10,-10:0.1:10, (x,y) -> airyai(x + y*im)/(x+y*im)^10 |> abs |> log10,fill=true)


Out[17]:

Heatmap


In [18]:
x = -2:0.1:2;
y = x;
z = [exp(-(x^2+y^2)) for x in x, y in y];

heatmap(x,y,z)


Out[18]:

Surface


In [19]:
surface(x,y,z)


Out[19]:

In [20]:
surface(x,y,(x,y) -> exp(-(x^2+y^2)))


Out[20]:

In [21]:
wireframe(x,y,(x,y) -> exp(-(x^2+y^2)))


Out[21]:

3D


In [22]:
plot3d(sin,cos,identity,-2pi,2pi)


Out[22]:

Styling

Linestyles


In [23]:
plot(sin,-pi:0.1:pi,line=(:red,10,:dot),label="sin")


Out[23]:

In [24]:
plot(sin,-pi:0.1:pi,line=(:solid,10,:cyan),label="sin",m=(3,:cross,:yellow))


Out[24]:

Texts


In [25]:
bar(["Episode 1","Episode 2", "Episode 3",
        "A New Hope", "The Empire Strikes Back","The Return of the Jedi"],
    [0,2,2,20,30,20]
)


Out[25]:

In [26]:
bar(["Episode 1","Episode 2", "Episode 3",
        "A New Hope", "The Empire \n Strikes Back","The Return \n of the Jedi"],
    [0,2,2,20,30,20]
)


Out[26]:

In [27]:
bar(["Episode 1","Episode 2", "Episode 3",
        "A New Hope", "The Empire \n Strikes Back","The Return \n of the Jedi"],
    [0,2,2,20,30,20],
    legend = false
)


Out[27]:

In [28]:
bar(["Episode 1","Episode 2", "Episode 3",
        "A New Hope", "The Empire \n Strikes Back","The Return \n of the Jedi"],
    [0,2,2,20,30,20],
    legend=false,
    title="Favorite Star Wars Movie",
    xlabel="Episode",
    ylabel="Awesomeness"
)


Out[28]:

In [29]:
bar(["Episode 1","Episode 2", "Episode 3",
        "A New Hope", "The Empire \n Strikes Back","The Return \n of the Jedi"],
    [0,2,2,20,30,20],
    legend=false,
    title="Favorite Star Wars Movie",
    xlabel="Episode",
    ylabel="Awesomeness",
    annotations=(0,1,"Jar Jar Binks Fail")
)


Out[29]:

In [30]:
bar(["Episode 1","Episode 2", "Episode 3",
        "A New Hope", "The Empire \n Strikes Back","The Return \n of the Jedi"],
    [0,2,2,20,30,20],
    legend=false,
    title="Favorite Star Wars Movie",
    xlabel="Episode",
    ylabel="Awesomeness",
    annotations=[(0.5,3,text("Jar Jar Binks \n Fail",10,:red)),(4.5,33,"Peak")],
    
)


Out[30]:

In [31]:
bar(["Episode 1","Episode 2", "Episode 3",
        "A New Hope", "The Empire \n Strikes Back","The Return \n of the Jedi"],
    [0,2,2,20,30,20],
    legend=false,
    title="Favorite Star Wars Movie",
    xlabel="Episode",
    ylabel="Awesomeness",
    annotations=[(0.5,3,text("Jar Jar Binks \n Fail",10,:red)),(4.5,33,"Peak")],
    ylims=[0,35]
)


Out[31]:

In [32]:
bar(["Episode 1","Episode 2", "Episode 3",
        "A New Hope", "The Empire \n Strikes Back","The Return \n of the Jedi"],
    [0,2,2,20,30,20],
    legend=false,
    title="Favorite Star Wars Movie",
    xlabel="Episode",
    ylabel="Awesomeness",
    annotations=[(0.5,3,text("Jar Jar Binks \n Fail",10,:red)),(4.5,33,"Peak")],
    ylims=[0,35]
)


Out[32]:

In [33]:
bar(["Episode 1","Episode 2", "Episode 3",
        "A New Hope", "The Empire \n Strikes Back","The Return \n of the Jedi"],
    [0,2,2,20,30,20]
)


Out[33]:

In [34]:
bar(["Episode 1","Episode 2", "Episode 3",
        "A New Hope", "The Empire <br> Strikes Back","The Return <br> of the Jedi"],
    [0,2,2,20,30,20]
)
#legend(false)
title!("Favorite Star Wars Movie")
xlabel!("Episode")
ylabel!("Aswesomeness")
annotate!([(0.5,3,text("Jar Jar Binks <br> Fail",10,:red)),(4.5,33,"Peak")])
ylims!(0,35)


Out[34]:

Subplot


In [35]:
plot(sin,-pi:0.1:pi)
plot!(cos,-pi:0.1:pi)
scatter!(tan,rand(-pi:0.3:pi,10))


Out[35]:

In [36]:
p1 = plot(sin,-pi:0.1:pi);
p2 = plot(cos,-pi:0.1:pi);
p3 = plot(tan,-pi:0.1:pi);
plot(p1,p2,p3,layout=3)


Out[36]:

In [37]:
l = @layout([a{0.3w} b; c])


Out[37]:
Plots.GridLayout(2, 1)

In [38]:
plot(p1,p2,p3,layout=l)


Out[38]:

Fun - XKCD Style


In [39]:
pyplot(); Plots.PyPlot.xkcd();

In [40]:
x = 1:0.1:10; plot(sin,x,margin=1cm)


Out[40]:

Animations


In [41]:
gr()
@gif for i in 0:0.1:2pi
    plot(x -> sin(x+i),0:0.1:2pi)
end


INFO: Saved animation to /Users/tauu/Documents/Work/Reise/Vancouver2017/JuliaCourse/tmp.gif
Out[41]:

Exercises

Task 1

Create a plot containing the functions: $x$, $\sin{x}$, and $\log{x}$, such that the plots of all functions can be distinguised close to x=0.

Task 2

Recreate the following image.

The heart shape may be generated using the parametrization

$$ \begin{align*} h \colon &[-\pi,\pi] \to \mathbb{R}\\ &t \mapsto (16sin^3(t), 13cos(t)-5cos(2t)-2cos(3t)-cos(4t)). % h_x(t) &= 16sin^3(t) \\ % h_y(t) &= 13cos(t)-5cos(2t)-2cos(3t)-cos(4t) \end{align*} $$

Hint: The package LaTeXStrings is useful for createing the title.

Task 3

Create a histogram plot of the slide data provided in "slideTimes.csv".

Task 4

Create the following animation displaying the n-th complex roots of 1 for n between 1 and 20.

Bonus Task

Create the following gif.


In [ ]: