3.4 Plots

For image types from libraries that Books.jl doesn’t know about such as plotting types from Plots.jl and Makie.jl, it is required to extend two methods. First of all, extend Books.is_image so that it returns true for the figure type of the respective plotting library. For example for Plots.jl set

import Books

Books.is_image(plot::Plots.Plot) = true

and extend Books.svg and Books.png too. For example, for Plots.jl:

Books.svg(svg_path::String, p::Plots.Plot) = savefig(p, svg_path)

Adding plots to books is actually a bit tricky, because we want to show vector graphics (SVG) on the web, but these are not supported (well) by LaTeX. Therefore, portable network graphics (PNG) images are also created and passed to LaTeX, so set Books.png too:

Books.png(png_path::String, p::Plots.Plot) = savefig(p, png_path)

Then, plotting works:

function example_plot()
    I = 1:30
    plot(I, I.^2)
Figure 2: Example plot.

For multiple images, use Options.(objects, paths):

function multiple_example_plots()
    filenames = ["example_plot_$i" for i in 2:3]
    I = 1:30
    objects = [
        plot(I, I.^2),
        scatter(I, I.^3)
    return Options.(objects, filenames)

Resulting in one Plots.jl (Figure 3) and one CairoMakie.jl (Figure 4) plot:

Figure 3: Example plot 2.
Figure 4: Example plot 3.

To change the size, change the resolution of the image:

function image_options_plot()
    I = 1:30
    fig = Figure(; resolution=(600, 140))
    ax = Axis(fig[1, 1]; xlabel="x", ylabel="y")
    scatterlines!(ax, I, 3 .* sin.(I))
    return fig
Figure 5: Image options plot.

And, for adjusting the caption, use Options:

function combined_options_plot()
    fg = image_options_plot()
    Options(fg; caption="Sine function.")
Sine function.

or the caption can be specified in the Markdown file:

p = M.image_options_plot()
Options(p; caption="Label specified in Markdown.")
Label specified in Markdown.

function plotsjl()
    p = plot(1:10, 1:2:20)
    caption = "An example plot with Plots.jl."
    # Label defaults to `nothing`, which will not create a cross-reference.
    label = missing
    Options(p; caption, label)
An example plot with Plots.jl.

This time, we also pass link_attributes to Pandoc (Figure 6) to shrink the image width on the page:

function makiejl()
    x = range(0, 10, length=100)
    y = sin.(x)
    p = lines(x, y)
    caption = "An example plot with Makie.jl."
    label = "makie"
    link_attributes = "width=70%"
    Options(p; caption, label, link_attributes)
Figure 6: An example plot with Makie.jl.

CC BY-NC-SA 4.0 Rik Huijzer, and contributors