Plots 2: Basic plot Function
I think this will be one of my last blog about plots because I’m hasty. I want to explore genetic algorithms based on Driving a car with genetic algorithm. Any way let’s dive in. The Jupyter notebooks for this blog is available here https://gitlab.com/data-science-with-julia/code/-/blob/master/plots.ipynb.
Plotting Sin and Cos
To start with let’s define θ
to be from -2π
to 2π
with steps of 0.01
as shown below:
θ = -2π : 0.01 : 2π
Output:
-6.283185307179586:0.01:6.276814692820414
Now lets plot cos
and sin
values of θ
plot(
θ, [sin.(θ), cos.(θ)],
title = "sin and cos plots",
xlabel = "Radians",
ylabel = "Amplitude",
label = ["sin(θ)" "cos(θ)"],
ylims = (-1.5, 1.5),
xlims = (-7, 7)
)
Output:
So, what just happened? We have a function called plot()
:
plot()
To that we pass the first argument to be θ
:
plot(θ)
the second argument to be an array of sin
and cos
of θ
:
plot(θ, [sin.(θ), cos.(θ)])
apart from that we pass the following attributes too:
title
: Self explanatoryxlabel
: The text that must appear for the x-axisylabel
: The text that must appear for the y-axislabel
: The legend of the curves shown in top rightxlims
andylims
: The minimum and maximum of coordinates that needs to be displayed for the plot, these acceptsTuple
as argument
Building a Plot
Its not that you have to create a plot all in a go, you can build it part by part, you can see blow that we plot sin
of θ
below, we have set linewidth = 3
so it appears nice and thick, we have set the color to be purple, and its label to be sin θ:
p = plot(θ, sin.(θ), color = "purple", linewidth = 3, label = "sin θ")
so you get a plot as shown:
we have assigned the output of the above plot to a variable named p
, so in the future this could be modified. Now lets add cos
plot to p
, for that look at the code below:
plot!(p, θ, cos.(θ), color = "red", linewidth = 3, label = "cos θ")
Output:
so it is the same with just one difference, we are mutating p
by passing it to the plot!()
function. Notice the exclamation mark !
in the plot!()
and it accepts a plot as its first argument which it changes. Now in the code below we further decorate p
with title, labels and limits:
plot!(
p,
title = "sin and cos plots",
xlabel = "Radians",
ylabel = "Amplitude",
ylims = (-1.5, 1.5),
xlims = (-7, 7)
)
Output: