iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📊

Introduction to Plots.jl

に公開
2025/11/12
1件

Introduction

At the time of writing, according to juliapackages.com, Julia's most popular general-purpose visualization package was Plots.jl. However, I didn't find the official tutorial or samples to be very intuitive. (Note: According to star-history.com, it seems to have been overtaken by Makie.jl around 2023. Also, the current tutorial is much easier to understand than before.) Therefore, I created this note to help you take the first steps with Plots.jl through even simpler and as easy-as-possible examples.

Installation

You need to install Plots.jl in advance by running add Plots in Julia's package mode. In your script or notebook, declare using Plots.

# using Pkg
# Pkg.add("Plots")
using Plots

Hello World!

You can plot by passing a function name to plot(). If no specific options are provided, it will result in a (quite smooth) line graph.

plot(sin)

You can also pass custom functions. You can refer to this for how to declare functions.

f(x) = x^2
plot(f)

If you want to write it in a single line, pass an anonymous function.

plot(x->x^2)

You can also pass two arrays to draw line graphs or scatter plots using them as the x-axis and y-axis values respectively.

X = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Y = [0, 1, 0, 2, 0, 4, 0, 8, 0, 4, 4]

plot(X, Y)

Additional Options

If you want to change the title, axis labels, markers, line colors, etc., you can add the following options. Those introduced below are just a few examples; the full list is available here.

Strings

Description Abbreviation Option Argument Example
Title title "", "hello"
Legend label "", "hello"
x-axis label xlabel "", "hello"
y-axis label ylabel "", "hello"
Title font size titlefontsize 12, 18
Legend font size legendfontsize 12, 18
Tick font size tickfontsize 12, 18
Axis label font size guidefont 12, 18
x-axis label font size xguidefont 12, 18
y-axis label font size yguidefont 12, 18

Axis

Description Abbreviation Option Argument Example
Borders and axes framestyle :box, :semi, :origin, :zerolines, :grid :none
Show x-axis xshowaxis true, false
Show y-axis yshowaxis true, false
x-axis display range xlims (-1,1), (0,2π)
y-axis display range ylims (-1,1), (0,2π)
x-axis scale xscale :log10, :ln, :log2
y-axis scale yscale :log10, :ln, :log2
x-axis tick positions xticks 0:0.1:2, [1,3,4]
y-axis tick positions yticks 0:0.1:2, [1,3,4]
x-axis grid lines xgrid true, false
y-axis grid lines ygrid true, false
x-axis minor grid lines xminorgrid true, false
y-axis minor grid lines yminorgrid true, false

Design

Description Abbreviation Option Argument Example
Plot type st seriestype :line, :scatter, :steppre, etc.
Line style (solid, dashed, etc.) ls linestyle :solid, :dash, :dot, etc.
Line alpha la linealpha 0.0, 0.2, 0.5, 1.0
Line width lw linewidth 1, 2, 4
Line color lc linecolor :red, :green, :blue, "#FF0000"
Fill alpha fa fillalpha 0.0, 0.2, 0.5, 1.0
Fill color fc fillcolor :red, :green, :blue, "#FF0000"
Marker shape markershape :circle, :square, :hexagon, etc.
Marker size ms markersize 20
Marker alpha markeralpha 0.0, 0.2, 0.5, 1.0
Marker color mc markercolor :red, :green, :blue, "#FF0000"
Marker stroke width msw markerstrokewidth 1, 2, 4
Marker stroke alpha markerstrokealpha 0.0, 0.2, 0.5, 1.0
Marker stroke color msc markerstrokecolor :red, :green, :blue, "#FF0000"
Marker stroke style (solid, dotted, etc.) markerstrokestyle :solid, :dot
Legend position legend :bottomleft, :topright, etc.
Legend background color background_color_legend :red, "#FF0000", nothing
Legend border color foreground_color_legend :red, "#FF0000", nothing

Here is an example showing basic string and color scheme specifications.

plot(sin, title="title", label="label", xlabel="x", ylabel="y", lw=10, lc="#00C8AF", foreground_color_legend=:red)

Domain and Display Range

When plotting functions, the domain and sample interval are specified like -1:0.01:1. For the display range, specify xlims=(min, max) and ylims=(min, max) respectively. You may specify only one of them. When plotting arrays, you don't need to specify the number of samples, so you can write it like plot(X, Y, xlims=(-2*pi, 2*pi), ylims=(-0.5, 1)).

plot(-5:0.01:5, sin, xlims=(-2*pi,2*pi), ylims=(-0.5,1))

Scatter Plots

Scatter plots can be drawn by adding the st=:scatter option to plot() or by using scatter(). The basic usage is the same as plot().

plot(sin, st=:scatter)

scatter(sin)

Histograms

By passing an array, you can draw a histogram of its elements. Below, the normed=true option is used to draw a normalized histogram (where the total area is 1).

X = [1, 2, 3, 3, 4, 5, 5]

histogram(X, bins=range(0, 6, step=0.2), normed=true)

Example of a uniform distribution:

X = rand(10000)

histogram(X, bins=range(0, 1, step=0.02), normed=true)

Example of a normal distribution:

X = randn(10000)

histogram(X, bins=range(-5, 5, step=0.2), normed=true)

You can also pass two arrays to draw a 2D histogram. You can specify the color scheme using c=:heat. For color schemes, please refer to this page.

X = randn(1000)
Y = randn(1000)

histogram2d(X, Y, nbins=20, c=:heat)

Heatmaps

Just pass the domains for the x-axis and y-axis along with a two-variable function f. You can specify the color scheme using c=:thermal. For color schemes, please refer to this page.

f(x,y) = x^2 + y^2

heatmap(-3:0.01:3, -2:0.01:2, f, c=:thermal)

You can also pass a 2D array.

Z = randn(20,20)

heatmap(Z)

You can also pass 1D arrays for the x-axis and y-axis.

X = [0.1*i for i in 0:20]
Y = [0.1*i for i in 0:20]
Z = randn(21,21)

heatmap(X, Y, Z)

3D Plots

The basic usage is simply replacing the heatmap above with surface.

f(x,y) = x^2 + y^2

surface(-3:0.01:3, -2:0.01:2, f, c=:thermal)

Z = randn(21,21)

surface(Z)

Multivariable Functions

You might often encounter errors and get stuck when plotting multivariable functions. While two-variable functions can be visualized with heatmaps or 3D plots, it becomes more difficult with more variables. In such cases, let's create and plot a single-variable function by projecting it as follows:

f(x,y,z) = x^2 + y^2 + z^2

plot(x->f(x,0,0))
f(x,y,z) = x^2 + y^2 + z^2
g(x) = f(x,0,0)

plot(g)

Subplots

Here are four equivalent ways to write this. Each has its pros and cons, so please use them as appropriate.

plt1 = plot(sin, label="")
plt2 = plot(cos, label="")
plt3 = plot(exp, label="")
plt4 = plot(abs, label="")

plot(plt1, plt2, plt3, plt4, layout = (2, 2))

Loops are easy to use with the following notation:

plt = []

push!(plt, plot(sin, label=""))
push!(plt, plot(cos, label=""))
push!(plt, plot(exp, label=""))
push!(plt, plot(abs, label=""))

plot(plt..., layout = (2, 2))

plot(
    plot(sin, label=""),
    plot(cos, label=""),
    plot(exp, label=""),
    plot(abs, label=""),
    layout = (2, 2)
)

plot(
    plot(x->sin(x), label=""),
    plot(x->cos(x), label=""),
    plot(x->exp(x), label=""),
    plot(x->abs(x), label=""),
    layout = (2, 2)
)

The same applies to anonymous functions:

plot(
    plot(x->x^1, label=""),
    plot(x->x^2, label=""),
    plot(x->x^3, label=""),
    plot(x->x^4, label=""),
    layout = (2, 2)
)

Overlaying Graphs

To overlay graphs, use plot!().

plt = plot(sin, label="sin")
plot!(plt, cos, label="cos")

You can also overlay line graphs and scatter plots.

X = [i for i in 0:10]
Y = sin.(X)

plt = plot(0:0.1:10, sin, label="function")
scatter!(plt, X, Y, label="array")

Text

Besides title, label, xlabel, and ylabel, there are times when you want to draw text at specific coordinates. Just like overlaying graphs, you can draw text using plot!(annotations=(x_coordinate, y_coordinate, ("string", font_size(integer), angle(float), position))). Specifying font colors often doesn't work well, so it's not recommended (it likely depends on the backend). Additionally, you can use xticks!([0,1,3], ["A", "B", "C"]) to assign custom strings to the tick values.

plot(-3:0.1:3, sin, title="example", label="label", xlabel="xlabel", ylabel="ylabel")

# Example of specifying one by one:
plot!(annotations=(-pi/2, -1, ("min", 8, 0.0, :bottom)))
plot!(annotations=(0, 0, ("origin", 8, 0.0, :center)))
plot!(annotations=(pi/2, 1, ("max", 8, 0.0, :top)))

# Example of specifying one by one:
annotate!(-1, 0.5, "aaaaa")

# Example of passing as an array:
plot!(annotations=[
    (pi/2, 0.0, ("a", 8, 0.0, :center)),
    (pi/2, 0.1, ("b", 8, 45.0, :center)),
    (pi/2, 0.2, ("c", 8, 90.0, :center)),
])

# Example of changing axis text:
xticks!([0,1,3], ["A", "B", "C"])

Saving

When saving to a file, specify the size and extension as shown below. SVG is easy to handle among vector images and can be pasted into PowerPoint by dragging and dropping. When uploading to Zenn, converting to GIF makes it less prone to degradation.

plt = plot(sin, size=(420,300), fmt=:svg)
savefig(plt, "plot.svg")
display(plt)

Animation

You can also output GIF animations. (Since FFmpeg is required, you need to follow these instructions to install it and add the bin folder to your environment variable path. Note: When I updated Julia, I encountered an UndefVarError: ffmpeg not defined error, but it started working after running add Plots and build Plots again in package mode (Reference).)

anim = Animation()

for i in 1:10
    plt = plot(x->sin(i*x), title="i = "*string(i), label="")
    frame(anim, plt)
end

gif(anim, "plot.gif", fps = 2)

CSV Files

If you want to read and plot external files such as CSV files, first use CSV.jl or DataFrames.jl to store the data as an array. Once you have it as an array, you can plot it as explained earlier.

Tips

Example of hiding the legend
plot(sin, label="")

Example of plotting an anonymous function
plot(x->x*sin(x^2), label="")

Semi-log plot
plot(0.1:0.1:10, x->x, yscale=:log10, label="")

Overlaying graphs in a loop
plt = plot()
for i in 1:10
    plot!(plt, x->exp(-x^(2*i)), label=string(i), legend=:topleft, xlim=(-2,2))
end
plot(plt)

Arranging graphs in a loop
plt = []
for i in 1:9
    push!(plt, plot(x->sin(x)^i, title=string(i), label=""))
end
plot(plt...)

A supplement on the "splat" operator used here. From the results of the execution below, we can see that println(A[1],A[2],A[3],A[4]) and println(A...) are equivalent notations.

A = [3,4,5,6]
println(A[1],A[2],A[3],A[4])
println(A...)
println(A)
3456
3456
[3, 4, 5, 6]
Example of overlaying a line graph and a histogram
f(x) = exp(-x^2/2) / sqrt(2*pi)
X = randn(1000)
Y = [-0.01-0.0001*i for i in 1:1000]

plt = histogram(X, bins=range(-5,5,step=0.2), ylims=(-0.14,), normed=true, label="Histogram", fa=0.3, fc=1, lc="#FFFFFF")
plot!(plt, f, lw=2, lc="#393e46", label="Exact PDF")

Example of overlaying a line graph, histogram, and scatter plot
f(x) = exp(-x^2/2) / sqrt(2*pi)
X = randn(1000)
Y = [-0.01-0.00005*i for i in 1:1000]

plt = histogram(X, bins=range(-5,5,step=0.2), ylims=(-0.7,), normed=true, label="Histogram", fa=0.3, fc=1, lc="#FFFFFF")
scatter!(plt, X, Y, xlims=(-5,5), ms=1, msw=0, mc="#3261AB", label="Sample")
plot!(plt, f, lw=2, lc="#393e46", label="Exact PDF")

Example of overlaying a 2D histogram and samples
X = randn(1000)
Y = randn(1000)

histogram2d(X, Y, nbins=20, c=:heat)
scatter!(X, Y, mc="#000000", msw=0, ms=1, label="")

Using LaTeX
# using Pkg
# Pkg.add("LaTeXStrings")
using LaTeXStrings
plot(sin, xlabel=L"x", ylabel=L"\sin(x)")

Depicting energy levels of a hydrogen-like atom
E(Z,n) = -Z^2/(2*n^2)

plot(xlims=(0,3), xshowaxis=false, xgrid=false, ylabel="\$\\mathrm{Energy~Level~/~}E_\\mathrm{h}\\")

annotate!(0.5, E(3,1)-0.4, "\$\\mathrm{H}\\", 12)
annotate!(1.5, E(3,1)-0.4, "\$\\mathrm{He}^+\\", 12)
annotate!(2.5, E(3,1)-0.4, "\$\\mathrm{Li}^{2+}\\", 12)

for i in 1:30
    plot!([0.1,0.9], fill(E(1,i),2), label="", lc=:darkblue)
    plot!([1.1,1.9], fill(E(2,i),2), label="", lc=:darkblue)
    plot!([2.1,2.9], fill(E(3,i),2), label="", lc=:darkblue)
end

plot!()

Example of changing margins
plot(sin, left_margin=Plots.Measures.Length(:mm, 50.0))

Image quality:
It seems you can also change the DPI.
https://github.com/genkuroki/public/blob/main/0026/dpi of plot.ipynb

Operating Environment

versioninfo()
Julia Version 1.6.2
Commit 1b93d53fc4 (2021-07-14 15:36 UTC)
Platform Info:
  OS: Windows (x86_64-w64-mingw32)
  CPU: Intel(R) Core(TM) i7-4650U CPU @ 1.70GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-11.0.1 (ORCJIT, haswell)

References

The data for the Jupyter Notebook that this article is based on can be found at the link below.
https://gist.github.com/ohno/78d55921c3f88b50a7fb1835be132bcd

The following service was used for converting SVG to GIF images.

https://imageconvert.org/svg-to-gif

Discussion