Plot Matrices, Formulas in Julia with Typst (or latex)

I often had the problem in the past, how to make complex plots with typical latex-elements like Matrices, Formulas etc. They frequently break when in Illustrator (plugins exist, but still… buggy for me), PowerPoint is not really re-usable etc.

For a talk at https://cuttingeegx.org/ I tried to push what Julia / https://makie.org/ can do for me on this issue. I wanted to have a quite complex plot, that I’d typically do in Illustrator, completely in Julia – and succeeded 🎉

Figure was 100% plotted via Julia / Makie.jl / MakieTex.jl

What follows is a short tutorial on how I plotted the matrix. Note that in the following I am using typst rather than LaTeX – a sane, modern, open-source replacement.


using MakieTeX, CairoMakie,Format

# convert a list of matrices to a typst-matrix
function gen_typst_matrix(str,args...;)
	# for convenience, we define a new typst command
	out = typst"""
	#let cm(x, color) = text(fill: color)[$#x$];"
	$mat(delim:\"[\",
	"""
	payload = format.(str,args...)
	for k = 1:size(payload,2)
		out = out * join(payload[:,k],',') * ";"
	end
	out = out*typst")$"
	
end

Next we define some colors and a color-conversion function

rgba_to_typst(c) = format("rgb({}%,{}%,{}%,{}%)",c.r*100,c.g*100,c.b*100,c.alpha*100)
end

colorlist = cgrad(:batlow,10;categorical=true)|>collect

Next we convert a matrix to Typst & add the color using our predefined cm command

typst_mat = gen_typst_matrix(
"cm({:.1f},#{})",
rand(Int,8,5),
repeat(rgba_to_typst.(colorlist),1,5))

Now we use the MakieTex function LTeX to convert it from Typst to PDF to Makie

LTeX(TypstDocument(typst_mat),scale=3); # scale = 3 to fill the figure

Tada 🎉

We can also combine this figure easily with other Typst things e.g.

LTeX(fig[2,1],TypstDocument(typst"$lambda = rho / phi$"),scale = 3)

or of course, a plot

r = 0:0.1:10 .*Ï€
ax = lines(fig[1:2,2],r.*sin.(r),r.*cos.(r),color=r)
hidespines!(ax.axis);hidedecorations!(ax.axis)

Categorized: Blog

Tagged:

Leave a Reply