User Tools

Site Tools


julia> pkgchk( [ "julia" => v"1.0.2", "Plots" => v"0.21.0", "Distributions" => v"0.16.4", "LaTeXStrings" => v"1.0.2" ] )


Julia does not have just one or two, but multiple graphing packages. Many are not written natively in Julia, but are packages written other languages (such as Python's PyPlot). (From Julia's user perspective, the foreignness is hidden by Plots.jl.) Each graphics package has its own feature set and unique look.

Fortunately, Julia also has one meta-plotting package, that tries to offer one API that then interfaces to whichever graphics backend you may want to choose. This is Plots.jl. If you are lucky, you may never have to learn the ins and outs of the different backends. This cookbook is all about this Plots.jl package.

Most likely, you will find what you are looking for in the 2-D Gallery, 3-D Gallery, or Plot Extras Gallery.

The Plots package still has some bugs, but it is maturing quickly. The most solid backend seems to be the default gr. Yet, even then, sometimes, GKSTerm on macos suddenly vanishes, and the julia session freezes. Sometimes, you need to refresh GKSTerm with an explicit display(p) (where p is the plot). etc.

On the REPL, by default, if the answer to the last statement is a Plot object, then it is automatically displayed. Note that this also means that if the last statement is a loop (e.g., to add multiple points), then no output will be displayed. In this case, you must assign the plot to a variable, and then call display(p) (or simply p on the REPL. See the grayscale example below.

A Quick X-Y Plot Example

julia> using Plots

julia> xs= 0 : 2*pi/10 : 2*pi;

julia> ydata= [sin.(xs) cos.(xs) 2*sin.(xs) 2*cos.(xs)];		# 10 data points in 4 series

julia> labels= ["Apples" "Oranges" "Hats" "Shoes"];    # Row Vector (1x Matrix!)

julia> markershapes= [:circle, :star5];     # Marker shapes in a column vector: applies to data points

julia> markercolors= [:green :orange :black :purple :red  :yellow :brown :white];

julia> plot( xs, ydata, size=[1000,400], xlim=[1,7], label=labels, shape=markershapes, color=markercolors, markersize=10, title="It Glitters!" )

julia> plot!( annotation=[ (1,1,"Look up!") ])

julia> savefig( "plotting/glitterplot.png" )

julia> savefig( "plotting/glitterplot.pdf" )

Common Plot Commands / Types

Line (XY) Plot

julia> using Plots

julia> plot( 1:100, sqrt.(1:100), labels="Square Root", size=[600,240] )

julia> savefig("plotting/samplelineplot.png")

Scatter Plot

julia> using Plots

julia> scatter( 1:16, sqrt.(1:16), labels="Square Root", size=[600,240] )

julia> savefig("plotting/samplescatter.png")

Bar Plot

julia> using Plots

julia> bar( 1:10, sin.(1:10), labels="10 sin values", size=[600,240] )

julia> savefig("plotting/samplebar.png")


julia> using Plots

julia> histogram( randn(1000), bins=20, labels="1000 Normal Draws", size=[600,240] )

julia> savefig("plotting/samplehistogram.png")

Output to File

The most common output formats are .png, .pdf, and .svg. savefig("ab.svg") is smart enough to save the last plot in svg format.

Further Plot Feature: Adding Text or Math to a Plot

Use plot! and text().

julia> using Plots

julia> using LaTeXStrings

julia> mathystring1 = L"\mbox{Title is } \sqrt{x}";

julia> mathystring2 = L"y= \sqrt{\frac{x^2}{x}}";

julia> plot( 1:100, sqrt.(1:100), title= mathystring1, legend=false, annotation=[(80, 6, mathystring2), (25,8,text( "redleft", 18,:red,:left))], size=[600,240] )

julia> annotate!( [ (25, 9, text("blueright",14,:blue,:right)), (25, 10, text("greencenter",10,:green,:center)) ] )  ## to add text later

julia> savefig("plotting/sampleannotated.png")

  • FIXME How do I shift a text annotation up, left, right, down relative to a marker (coordinate)?

Further Plot Feature: Adding Vertical or Horizontal Lines to a Plot

julia> using Plots

julia> plot( 1:100, sqrt.(1:100), legend=false, size=[600,240] )

julia> vline!([20.0, 50.0], color=[:blue,:red], width=[5,10], alpha=0.3)

julia> hline!( [collect(1:10)], color=[:blue,:red,:green], width=[1,4], alpha=collect(0.1:0.1:1.0))  ## this does not cycle correctly

julia> savefig("plotting/samplevhlines.png")

Multiple Plots in Layout


julia> using Plots

julia> plotleft= plot( 1:100, sqrt.(1:100), title="sqrt" )

julia> plotright= plot( 1:100, sin.(1:100), title="sin" )

julia> plot( plotleft, plotright, layout= 2 )

julia> savefig("plotting/samplelayout.png")

Warning When Reusing Plot Objects

julia> using Plots

julia> plotleft= plot( 1:100, sqrt.(1:100), title="sqrt" )

julia> plotright= plot( plotleft, title="another sqrt" )

julia> plot( plotleft, plotright, layout= 2 )

julia> savefig("plotting/samplelayoutwrong.png")

Alas, what's wrong with the left plot? The problem is that the plotright object is the same object as the plotleft object, and changes it around. What is needed is a deepcopy.

Deepcopy and Layouts

julia> using Plots

julia> plotleft= plot( 1:100, sqrt.(1:100), title="sqrt" )

julia> plotright= plot( deepcopy(plotleft), title="another sqrt" )   ## now it is correct

julia> plot( plotleft, plotright, layout= 2 )

julia> savefig("plotting/samplelayoutright.png")

Plot Attributes

The Most Common Plot Attributes

Overall Plot

Attribute Sample Explanation
title ="My Plot" The headline over the plot. Also called guide.
xlim,ylim =[1,10] The (X)-axis or (Y)-axis range
xlabel,ylabel ="y values" The label on the (X) or (Y)-axis
legend =false whether to draw a legend at all
xaxis,yaxis =:log whether the (X)- or (Y) axis should be a log-axis
grid =false whether to draw a grid or not
ticks =false whether to draw tickmarks or not
size =[640,480] one way to specify the size of the plot
dpi =72 another way to specify the size and resolution of the plot
layout =4 how many plots to set into a grid


Attribute Sample Explanation
labels =[a b c] the names for the legend
width =[3 5] the width of lines, here 3 for the first, 5 for the second series
linecolor =[:yellow :blue] the color of the lines or markers
linestyle =[:solid :dash] the type of line (also seriestype)
markershape =[:hexagon :square] the type of symbol
color =[:red :green] marker colors
markersize =[0.2 0.4] the size of the symbol

Julia has an unusual way to add text to a plot. It does not use an addtext() command. Instead, you use plot!() (the colon means not to replace but to add to the current plot) with an annotation:

Attribute Sample Explanation
annotate =[ (1.2, 2.9, "my text"), (2.1, 1.2, "more text" ),] Plots' way to add text

Setting Default Plot Attributes

 julia> default(; size=[800,400])

Colors and Grayscales

Color Integers

julia> using Plots

julia> vline( collect(1:32), width=20, color=collect(1:32), size=[1000,200], xlim=[0,33], legend=false )

julia> savefig("plotting/colors-numeric.png")

You can also specify colors as RGB. For example, RGB(0.0,0.0,1.0) is blue.


julia> using Plots

julia> p= plot( [0.0,1.0], [0.0,1.0], color=Gray(0.5), w=60, size=[1000,200] )  ## assign to use below

julia> for g=range( 0.0, stop=1.0, length=24 ) vline!(p, [g], color=Gray(g), w=30, legend=false) end

julia> display(p)	## needed, because the 'for' statement returns 'nothing'.

julia> savefig("plotting/grays-numeric.png")

Weird Cycling

  • FIXME Why does the following grayscale cycling not work? It cycles at 0.33, rather than 1.0.
julia> using Plots

julia> p=plot( [0.0,1.0], [0.0,1.0], color=Gray(0.5), w=60, size=[1000,200] )

julia> g= range( 0.0, stop=1.0, length=32 )

julia> vline!( p, g, color=Gray.( reshape( g, length(g), 1) ), w=30 )  ## cycles too quickly

Color Ranges

FIXME Add examples of some color schemes or ranges, preferably one that is also for colorblinds.

FIXME It would be nice to illustrate color wheels, color spectra, gradient spectra, and especially color-blind ones.

Line Styles

julia> using Plots

julia> linestyles= [ :auto, :solid, :dash, :dot, :dashdot, :dashdotdot ];

julia> annotations= [(5,i,string(linestyles[i])) for i in 1:length(linestyles)];

julia> hline( 1:length(linestyles), width=15, linestyle=linestyles, color=:orange, annotations=annotations, size=[800,200], ylim=[0,length(linestyles)+1], xlim=[0,10], legend=false )

julia> savefig("plotting/linestyles.png")

Marker Shapes

julia> using Plots

julia> bmarkerstyles= [ :circle, :rect, :star5, :diamond, :hexagon, :cross, :xcross, :utriangle, :dtriangle, :rtriangle, :ltriangle ];

julia> tmarkerstyles= [ :pentagon, :heptagon, :octagon, :star4, :star6, :star7, :star8, :vline, :hline, :+, :x ];

julia> x= collect(1:10)

julia>  scatter( x , fill(1, length(x)) , marker=10, markershape=bmarkerstyles, annotate=[ ( x[i], 0.2, string(bmarkerstyles[i])) for i in x ], size=[1000,200], axis=false, legend=false, ylim=[0,4] )

julia> scatter!( x , fill(3.5, length(x)) , marker=10, markershape=tmarkerstyles, annotate=[ ( x[i], 2.8, string(tmarkerstyles[i])) for i in x ] )

julia> savefig("plotting/markershapes.png")

(There is also :none and :auto.]

The Complete List of Plot Attributes

julia> using Plots

julia> plotattr()
Specify an attribute type to get a list of supported attributes. Options are Series, Subplot, Plot, Axis

julia> plotattr(:Plot)
Defined Plot attributes are:
background_color, background_color_outside, display_type, dpi, extra_kwargs, fontfamily, foreground_color, html_output_format, inset_subplots, layout, link, overwrite_figure, plot_title, pos, show, size, thickness_scaling, window_title

julia> plotattr(:Subplot)
Defined Subplot attributes are:
annotations, aspect_ratio, background_color_inside, background_color_legend, background_color_subplot, bottom_margin, camera, clims, color_palette, colorbar, colorbar_title, fontfamily_subplot, foreground_color_legend, foreground_color_subplot, foreground_color_title, framestyle, left_margin, legend, legendfontcolor, legendfontfamily, legendfonthalign, legendfontrotation, legendfontsize, legendfontvalign, legendtitle, margin, projection, right_margin, subplot_index, title, title_location, titlefontcolor, titlefontfamily, titlefonthalign, titlefontrotation, titlefontsize, titlefontvalign, top_margin

julia> plotattr(:Series)
Defined Series attributes are:
arrow, bar_edges, bar_position, bar_width, bins, contour_labels, contours, fill_z, fillalpha, fillcolor, fillrange, group, hover, label, levels, line_z, linealpha, linecolor, linestyle, linewidth, marker_z, markeralpha, markercolor, markershape, markersize, markerstrokealpha, markerstrokecolor, markerstrokestyle, markerstrokewidth, match_dimensions, normalize, orientation, primary, quiver, ribbon, series_annotations, seriesalpha, seriescolor, seriestype, smooth, stride, subplot, weights, x, xerror, y, yerror, z

julia> plotattr(:Axis)
Defined Axis attributes are:
discrete_values, flip, foreground_color_axis, foreground_color_border, foreground_color_grid, foreground_color_guide, foreground_color_minor_grid, foreground_color_text, formatter, grid, gridalpha, gridlinewidth, gridstyle, guide, guidefontcolor, guidefontfamily, guidefonthalign, guidefontrotation, guidefontsize, guidefontvalign, lims, link, minorgrid, minorgridalpha, minorgridlinewidth, minorgridstyle, minorticks, mirror, rotation, scale, showaxis, tick_direction, tickfontcolor, tickfontfamily, tickfonthalign, tickfontrotation, tickfontsize, tickfontvalign, ticks, widen

Details About A Specific Plot Attribute

julia> using Plots

julia> plotattr("arrow")
arrow {nothing (no arrows), Bool (if true, default arrows), Arrow object, or arg(s) that could be style or head length/widths}

Defines arrowheads that should be displayed at the end of path line segments (just before a NaN and the last non-NaN point).  Used in quiverplot, streamplot, or similar.
Series attribute,  default: nothing

Switching Backend

The default backend is GR. It is the least painful one to use, and the least buggy (as backend). You can switch backends, e.g., with julia> using Plots; pyplot()

GR Look

julia> using Plots

julia> plot( 1:10, sqrt.(1:10), labels="Square Root", size=[600,240] )

julia> scatter!( 1:10, sqrt.(1:10) )

julia> savefig("plotting/lookgr.png")

PyPlot Look

julia> using Plots; pyplot()

julia> plot( 1:10, sqrt.(1:10), labels="Square Root", size=[600,240] )

julia> scatter!( 1:10, sqrt.(1:10) )

julia> savefig("plotting/lookpyplot.png")


WARNING PlotlyJS is not Plotly. Avoid the latter.

WARNING For now, avoid the former, too. I could not manage to get it to install and work correctly. Saving figures by PlotlyJS requires installing and loading the ORCA package, too. It may also need something called Electron, something called Blink, and who knows what else.

For good use, PlotlyJS first also needs

julia> Pkg.add("Blink") using Blink; Blink.AtomShell.install() exit()

julia> Pkg.add("ORCA") using ORCA;

However, even then, it plots empty graphs:

julia> using Plots, ORCA; plotlyjs()

julia> plot( 1:10, sqrt.(1:10), labels="Square Root", size=[600,240] )

julia> scatter!( 1:10, sqrt.(1:10) )

julia> Plots.savefig("plotting/lookplotlyjs.png")  ## may require `Plots.savefig("plotting/lookplotlyjs.png")` instead

This is some interface flaw, because

julia> using PlotlyJS

julia> p= plot( 1:10, sqrt.(1:10), labels="Square Root", size=[600,240] )

julia> using ORCA

julia> savefig( p, "plotlyjs-example.png" )

works ok.


Gadfly is a native Julia plotting system based on Hadley Wickham's ggplot2. It is not integrated to be a backend for Plots.jl.


Useful Packages on Julia Repository

  • plotting, a major and versatile plotting package, but not integrated with Plots.jl. If you want to use this on macOS, install Cairo and FontConfig.


For a comparison of backends, see here. In brief,

Need Use
GUI GR, PyPlot, PlotlyJS, and InspectDR
Features GR, PyPlot, Plotly
Beauty Plotly PGFPlots

Plot Galleries

There are various other example galleries, but they are either not for Plots.jl or they are broken in the current Julia 1.0.0. Specifically:


Author Notes

Regenerate the figures with
[download only julia statements]
rm -rf plotting.jl ; grep '^julia>' plotting.txt | sed 's/julia> //' > plotting.jl ; julia plotting.jl
plotting.txt · Last modified: 2018/11/22 20:48 (external edit)