(Section 2.7) Plotting in Julia

Plotting is one of the bigger differences from Matlab, although, there are still many similarities.

The first thing we need to note is that plotting is not in Julia by default. You need to add plotting packages in order to get it.

In [3]:
Pkg.add("Plots")
Pkg.add("PyPlot")
INFO: Nothing to be done
INFO: METADATA is out-of-date — you may not have the latest version of Plots
INFO: Use `Pkg.update()` to get the latest versions of your packages
INFO: Nothing to be done
INFO: METADATA is out-of-date — you may not have the latest version of PyPlot
INFO: Use `Pkg.update()` to get the latest versions of your packages

These commands show "Nothing to be done" because I already have the packages! But if you don't, they will get them. You only need to do this once for your Julia, so I never have to run these commands again! Yay! Once I've run then, then I can make plots.

In [7]:
using Plots

This command loads the plotting library. So now we can make plots.

In [9]:
x = 0:0.1:1
y = cos(50*x)
Out[9]:
11-element Array{Float64,1}:
  1.0     
  0.283662
 -0.839072
 -0.759688
  0.408082
  0.991203
  0.154251
 -0.903692
 -0.666938
  0.525322
  0.964966
In [12]:
plotly()# this says to use the Plotly backend, which has nice interactive features
# but sends data over the internet :(
plot(x,y)
Out[12]:
In [14]:
pyplot() # This says to use the Pyplot backend, which keeps all data locally, 
# but doesn't have the interactive features. 
plot(x,y)
Out[14]:

You don't have to execute plotly() or pyplot() before each command, it'll remember.

In [18]:
x = 0:0.01:1
y = cos(50*x)
plot(x,y)
title!("Plot of x versus cos(50x)")
ylabel!("cos(50x)")
xlabel!("x")
Out[18]:
In [24]:
plot(x,cos(50*x),label="cos(50x)")
plot!(x,x,label="x") # add a second line
# A plot with two lines and a legend (Figure 2.3)
Out[24]:

Saving plots in Julia

If you want to include plots into your homework in Latex, you can save the plots.

In [26]:
savefig("myplot.pdf") # this saves a PDF file
savefig("myplot.png") # this saves a PNG file