Plots.jl is a non-traditional plotting library
The rapidly growing documentation is at http://docs.juliaplots.org/latest/
Plots.jl uses other plotting libraries as backends
UnicodePlots: Plots to unicode for no-display situations
Each of those is a separate plotting package, with a separate API. Each has their strengths and weaknesses. However, you'd have to learn 5 API's to use them all. Plots.jl reduces that to 1 API.
We will mostly rely on the default option, which is GR
. More about Backends.
using Plots
gr()
plot(rand(10,4)) # will use the default backend: GR
pyplot() # change backend to pyplot
plot(rand(10,4))
# plotlyjs.jl is currently having an unresolved bug for notebooks.
# this stuff only works in the terminal.
# https://github.com/sglyon/PlotlyJS.jl/issues/255
# plotlyjs() # change backend
# plot(rand(4,4))
.tex
code. # pgfplots()
# plot(rand(4,4))
# not in notebook!
# using PGFPlots
# x = [1,2,3]
# y = [2,4,1]
# PGFPlots.plot(x, y)
using LaTeXStrings
plot([plot(sin,0,10,label=L"$\sin(x)$"),plot(x->sqrt(2x),0,10,label=L"$\sqrt{2x}$")]...)
gr()
dd = vcat([[sin(i) sqrt(2i)] for i in 0:0.01:10]...);
p = plot(dd,label=[L"$\sin(x)$",L"$\sqrt{2x}$"])
# save this as:
# savefig("myfile.tex")
# savefig("myfile.pdf")
# savefig("myfile.svg")
The attributes work with each of the backends: http://docs.juliaplots.org/latest/attributes/
Compatibility of attributes is found in this chart: http://docs.juliaplots.org/latest/supported/
I find it easiest to use this page to find the right attributes: http://docs.juliaplots.org/latest/examples/pyplot/
gr() # back to GR
plot(rand(4,4),title="Test Title",label=["First" "Second" "Third" "Fourth"])
Let's try this out. Most of those examples come from the examples section of the plots website, so check it out for more.
# lesson 1: every column is a series
plot(rand(10)) # 1 col = 1 series
plot(rand(10,2)) # 2 cols = ...
#Â different linetypes
plot(rand(10,2),line=(:dot,:auto),marker=([:circle :diamond]),color=[:green :orange])
# histogram
histogram(randn(1000),nbins=20,legend=false,title="My Histogram!",ylabel="counts")
#Â add to an existing plot later...
plot(rand(100) / 3,reg=true,fill=(0,:red))
# ... with plot! or scatter!
scatter!(rand(100),marker=(2,:circle),color=:black)
layout
argument that you can specify.plot(rand(100,4),layout = 4,legend=false) # make 4 equal sized subplots
# specify the size of subplots
l = @layout([a{0.1h};b [c d; e]])
plot(randn(100,5),layout=l,t=[:line :histogram :scatter :steppre :bar],leg=false,ticks=nothing,border=false)
# we can also sequentially build plots and then stack them together
ty = [:line :histogram :scatter :steppre :bar]
p = Any[]
for typ in ty
push!(p,plot(rand(100),t=typ,title="$typ plot"))
end
plot(p...)
# ... and we can also add to the subplots in the same way
plot!(rand(100,5),t=:scatter)
# 3D plots
n = 100
ts = range(0,stop = 8Ï€, length = n)
x = ts .* map(cos,ts)
y = (0.1ts) .* map(sin,ts)
z = 1:n
plot(x,y,z,zcolor=reverse(z),m=(10,0.8,:blues,stroke(0)),leg=false,cbar=true,w=5)
plot!(zeros(n),zeros(n),1:n,w=10)
# plotlyjs is hard to beat for 3D
# unfortunately...
# plotlyjs()
# plot(x,y,z,zcolor=reverse(z),m=(10,0.8,:blues,stroke(0)),leg=false,cbar=true,w=5)
# plot!(zeros(n),zeros(n),1:n,w=10)
Any plot can be animated: see https://juliaplots.github.io
Recipes are abstract instructions for how to "build a plot" from data. There are multiple kinds of recipes. In execution order:
Since these extend Plots.jl itself, all of Plots.jl is accessible from the plotting commands that these make, and these recipes are accessible from each other.
[Series recipes are used to extend the compatibility of backends itself!]
DifferentialEquations.jl
by just calling plot(sol)
# CMS: Not working with Jupyter
#using DifferentialEquations
#f(u,p,t) = 1.01*u
#u0 = 1/2
#tspan = (0.0,1.0)
#prob = ODEProblem(f,u0,tspan)
#sol = solve(prob, Tsit5(), reltol=1e-8, abstol=1e-8)
#plot(sol,linewidth=5,title="Solution to the linear ODE with a thick line",
# xaxis="Time (t)",yaxis="u(t) (in μm)",label="My Thick Line!") # legend=false
#plot!(sol.t, t->0.5*exp(1.01t),lw=3,ls=:dash,label="True Solution!")
# the plot function still accepts keywords to set attributes:
#plot(sol,linewidth=5,title="Solution to the linear ODE with a thicker line",
# xaxis="Time (t)",yaxis="u(t) (in μm)",label="My Thick Line!")
# and we can add to the plot with plot!
#plot!(sol.t, t->0.5*exp(1.01t),lw=3,ls=:dash,label="True Solution!")
plot
methods at MomentOpt.jl@df
macro# basic example
using DataFrames, StatsPlots
df = DataFrame(a = 1:10, b = 10*rand(10), c = 10 * rand(10))
@df df plot(:a, [:b :c], colour = [:red :blue])
@df df scatter(:a, :b, markersize = 4 * log.(:c .+ 0.1))
using RDatasets
iris = dataset("datasets","iris")
@df iris marginalhist(:PetalLength,:PetalWidth,bins=30)
# correlation plot from a dataframe
@df iris corrplot([:SepalLength :SepalWidth :PetalLength :PetalWidth], grid = false, bins=20)
# corrplot from a matrix
M = randn(1000,4)
M[:,2] += 0.8sqrt.(abs.(M[:,1])) - 0.5M[:,3] .+ 5
M[:,3] -= 0.7M[:,1].^2 .+ 2
corrplot(M, label = ["x$i" for i=1:4])
#Â cornerplot for same matrix
cornerplot(M)
school = RDatasets.dataset("mlmRev","Hsb82")
println(first(school,6))
@df school density(:MAch, group = :Sx)
# use tuple of col names to group by more
@df school density(:MAch, group = (:Sx, :Sector), legend = :topleft)
singers = RDatasets.dataset("lattice","singer")
@df singers violin(:VoicePart,:Height,marker=(0.2,:blue,stroke(0)))
# @df singers boxplot!(:VoicePart,:Height)
# there is great support to plot distributinos
using Distributions
plot(Normal(3,5), fill=(0, .5,:orange))
dist = Gumbel(2)
plot(dist,lw=3,label="pdf",legend=:right,title="Dig that plot!")
scatter!(dist,func=cdf,alpha=0.3,label="cdf",xlabel="x")
vline!([median(dist)],color=:red,lw=3,label="median")
groupedbar(rand(10,3), bar_position = :dodge, bar_width=0.7)
groupedbar(rand(10,3), bar_position = :dodge, bar_width=0.7)
df = DataFrame(a = 1:50, b = 10*rand(50), c = 10 * rand(50))
@df df scatter(:a, :b, markersize = 4 * log.(:c .+ 0.1)) # like before
using Query
df |>
@filter(_.a > 5) |>
@map({_.b, d = _.c-10}) |>
@df scatter(:b, :d)