Chapter 17 Advanced Plotting using the Plots Package
Recall that using the
Makie package, one can consider plotting the polynomial by creating a function that pulls out the coefficients. However, the Plots package has a related package called RecipesBase that allows one to create a plotting recipe. That is if p is a Polynomial, then we can write plot(p) and it will plot the polynomial. Let’s see how and don’t forget to add the package and then enter using RecipesBase.
The package
RecipesBase includes the macro @recipe and although the documentation is sparse, this page is helpful in the background. The basic idea on a plot recipe is to do the following:
@recipe f(t::TheType,...) end
where
TheType is any datatype (either built-in or user defined). The recipe needs to return some number of vectors of points (depending on if it is 1D, 2D or a 3D plot). A simple version of this for type Polynomial is
@recipe function f(poly::Polynomial,xmin::Number=-2,xmax::Number=2)
xpts = LinRange(xmin,xmax,200)
ypts = map(x->eval(poly,x),xpts)
xpts,ypts
end
where line 2 creates an array of x values of length 200, then line 3 creates the y values for each x value. Line 4 returns a tuple of the pairs of points. We can now use this to plot a polynomial and we will need to
using Plots to:
plot(poly1)
and since we defaulted the plot range from -2 to 2, we get the following plot: \begin{center} \pgfplotsset{scale=0.6} \plot{plots/comp-type/plot01.tex}{poly} \end{center}
and if we want to specify the plotting range:
plot(poly1,0,4)
we get
Section 17.1 Changing other parameters
But wait... There’s more... One of the fantastic things about using
RecipesBase is that we can still use all of the other parameters associated with plot as we normally would. For example:
plot(poly1,0,4,linecolor=:orange,title="A quadratic", lw=2, legend=false)
produces the plot: % \begin{center} \pgfplotsset{scale=0.5} \plot{plots/comp-type/plot03.tex}{poly} \end{center}
Section 17.2 Setting Default parameters
Recipes also allow to set default parameters. Let’s say that if we want to always plot a polynomial green without a legend that we can put these default parameters in the recipe:
@recipe function f(poly::Polynomial,xmin::Number=-2,xmax::Number=2)
legend --> false
linecolor --> :green
xpts = LinRange(xmin,xmax,200)
ypts = map(x->eval(poly,x),xpts)
xpts,ypts
end
If we have this definition then
plot(poly1,0,4) produces the following plot: \begin{center} \pgfplotsset{scale=0.5} \plot{plots/comp-type/plot04.tex}{poly} \end{center}
