Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 40 ยท Data and Science

Plotting

Make line, scatter and bar plots in Julia with Plots.jl and Makie: labels, legends, multiple series, subplots, saving figures, and the first-plot delay.

A table of numbers rarely tells a story until you draw it. Julia has no single built-in plotting library. Instead there are several packages, and two matter most for beginners: Plots.jl, a friendly front end with a short syntax, and Makie, a powerful system for polished figures, interactivity and large data. Learning one makes the other easy to pick up.

In this lesson you will make line and scatter plots, add labels and legends, draw several series, build subplots, save to a file, and understand why the very first plot in a session takes a few seconds. Julia is not installed on this site, so the Julia code is read-only. The runnable examples draw the same figures with matplotlib in Python, which is a faithful stand-in for the ideas, though not for the exact function names.

Plots.jl: the quick route

Install the package with ] add Plots, then load it. A line plot takes the x values and the y values:

JULIA
using Plots

x = range(0, 2ฯ€, length = 100)

plot(x, sin.(x))

The dot after sin applies it to every element (see Broadcasting and the Dot Syntax). The call returns a plot object. In the REPL or in VS Code a window or pane opens to show it, and in a notebook the plot appears below the cell.

Labels, a title and a legend are keyword arguments:

JULIA
plot(x, sin.(x),
     label  = "sin(x)",
     xlabel = "angle (radians)",
     ylabel = "value",
     title  = "A sine wave",
     linewidth = 2,
     color  = :steelblue)

Colors can be symbols such as :red or :steelblue. linewidth, linestyle (:dash, :dot) and legend = :bottomleft are other common options.

Adding series and other plot types

A function whose name ends in ! adds to the current plot instead of creating a new one, following the convention for mutating functions:

JULIA
plot(x, sin.(x), label = "sin")
plot!(x, cos.(x), label = "cos")
scatter!(x[1:10:end], sin.(x[1:10:end]), label = "samples")

x[1:10:end] takes every tenth point, which is a range with a step. Other common plot types have their own function:

JULIA
scatter(xs, ys)                        # points only
bar(["a", "b", "c"], [3, 7, 5])        # bars
histogram(randn(1000), bins = 30)      # a histogram of random data
heatmap(rand(10, 10))                  # a matrix as colors
plot(xs, ys, seriestype = :scatter)    # the general form behind them all

You can also plot several columns at once by passing a matrix, where each column becomes a series, and label = ["one" "two"] (a row, with no commas) names them.

Two libraries, two goals

Plots.jl Short syntax, quick results, many backends.
Makie Fine control, interactivity, big data.

Start with Plots.jl; move to Makie when you need more control.

1 / 2

Subplots and layouts

To place several plots in one figure, create each plot, then combine them with layout:

JULIA
p1 = plot(x, sin.(x), title = "sin")
p2 = plot(x, cos.(x), title = "cos")
p3 = scatter(randn(50), randn(50), title = "noise")

plot(p1, p2, p3, layout = (1, 3), size = (900, 300))

layout = (1, 3) means one row and three columns, and size sets the width and height in pixels. For uneven grids, @layout [a; b c] describes a big plot on top and two below.

Saving figures

savefig writes the current plot, choosing the format from the file extension:

JULIA
savefig("waves.png")    # raster image
savefig("waves.svg")    # vector, scales without blur
savefig("waves.pdf")    # for papers

For a report you often want SVG or PDF, because they stay sharp when scaled. Use PNG for web pages and slides.

Backends

Plots.jl does not draw anything by itself. It describes the plot, and a backend does the drawing. The default, GR, is fast and good for most uses. Others include plotlyjs() for interactive web plots and pythonplot(), which calls matplotlib. You choose with gr() or plotlyjs() before plotting. That design is why the same plot(...) call can produce a static image or an interactive chart. Backends are loaded on demand, so install the one you want first.

Makie in brief

Makie has three layers of objects: a Figure (the canvas), an Axis (a pair of axes placed in the figure), and plot objects drawn into an axis. It is more verbose than Plots.jl but gives you control over every part:

JULIA
using CairoMakie        # a backend for static, publication-quality output

x = range(0, 2ฯ€, length = 100)

fig = Figure(size = (600, 400))
ax  = Axis(fig[1, 1], xlabel = "x", ylabel = "y", title = "Two waves")

lines!(ax, x, sin.(x), label = "sin")
lines!(ax, x, cos.(x), label = "cos")
axislegend(ax)

save("waves.png", fig)
fig                      # displays the figure

Makie has one backend per job: CairoMakie for vector and print quality, GLMakie for fast interactive 3D on the GPU, and WGLMakie for the browser. The fig[1, 1] notation places the axis in row 1, column 1 of a grid, so a second axis at fig[1, 2] sits beside it. The bang functions lines!, scatter! and barplot! draw into an existing axis.

Why the first plot is slow

You will notice that the first plot(...) in a fresh session takes several seconds, while the second takes a fraction of a second. Julia compiles each method the first time it runs with new argument types, and a plotting library has a lot of code to compile. This is "time to first plot". Later plots reuse the compiled code, so keep your Julia session open and avoid restarting it for every change. Tools such as Revise.jl reload edited code without a restart, and recent Julia versions cache more compiled code in packages to shorten the delay. How Julia Compiles Code explains the mechanism.

Plot from a running REPL or a notebook rather than running julia script.jl over and over. Every new process pays the first-plot cost again.

The same figures in matplotlib

The following examples reproduce the Julia plots above with matplotlib. The shapes of the calls differ slightly (plt.plot, plt.legend), but the workflow is identical: make data, draw, decorate, save. The site shows each open figure as an image under the code.

Python Lines, scatter points, labels and a legend

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Subplots: a layout of one row and three columns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Julia, layout = (1, 3) on the final plot call plays the role of plt.subplots(1, 3). Matplotlib creates the empty grid first and draws into it, while Plots.jl builds the plots first and arranges them afterwards.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the ! in plot! signal?

    By convention, functions ending in ! modify something that already exists. Here that is the current plot.
  2. 2. How do you write a figure to an SVG file with Plots.jl?

    savefig picks the output format from the file extension, so .svg gives a vector image.
  3. 3. Why is the first plot in a Julia session slow?

    Julia compiles methods on their first call. Later plots reuse the compiled code, so they are fast.
  4. 4. In Makie, what is an Axis?

    A Figure holds a layout, an Axis occupies a cell of it, and functions like lines! draw into the Axis.

Summary

  • Plots.jl gives short calls (plot, scatter, bar, histogram); Makie gives full control with Figure, Axis and lines!.
  • Labels, titles and colors are keyword arguments; plot! and other ! functions add to an existing plot.
  • Combine plots with layout, and save with savefig (Plots.jl) or save (Makie).
  • Backends do the drawing: GR by default, plotlyjs() for interactivity, CairoMakie for print quality.
  • The first plot in a session is slow because of compilation, so keep the session alive.

Next: model change over time and find best values in Differential Equations and Optimization.