mathmarkuptypesettingtypst

typst horizontal display of 2 images?


I am using typst to render some stuff, I want a side by side display of 2 images I gured out how to get things vertically:

#figure(
  (image("eulerian.svg", width: 10%),
  image("lagrangian.svg", width: 10%)).join(),
  caption: [A curious figure.],
) <glacier>

enter image description here

I am wondering how to get things horizontally now.


Solution

  • @honkbug gives a good example but without an explanation of the solution. Thus, I want to show the document and what happens with different parameters.

    1. Using grid

    Typst has a function grid, which allows us to arrange contents. And this is the function we can use to place subfigures.

    The most important parameter of grid is columns here:

    columns

    Either specify a track size array or provide an integer to create a grid with that many auto-sized columns.

    See doc for more details.

    When we give only one integer number, grid will create auto-sized columns and place contents automatically. Say we have two images and want to put them side by side; we can achieve this in this simple way:

    // A function to represent a virtual image
    #let vimg(body) = {
        rect(width: 10mm, height: 5mm)[
            #text(body)
        ]
    }
    
    #figure(
        grid(
            columns: 2,     // 2 means 2 auto-sized columns
            gutter: 2mm,    // space between columns
            vimg("1"),
            vimg("2"),
        ),
        caption: "some caption"
    )
    

    And we get this as a result: 2 images side by side

    We tell Typst we need two auto-sized columns with 2mm between them. But what if we provide more than two images? Let's test with 3:

    #figure(
        grid(
            columns: 2,
            gutter: 2mm,
            vimg("1"),
            vimg("2"),
            vimg("3"),
        ),
        caption: "some caption"
    )
    

    3 images in two columns Since we are still using two columns, Typst put the third one on the second row. And if we change the columns to 3, they will be in the same row.

    2. Using stack

    We can also use stack to achieve the goal:

    #figure(
        stack(
            dir: ltr,       // left-to-right
            spacing: 2mm,   // space between contents
            vimg("1"),
            vimg("2"),
        ),
        caption: "some caption"
    )
    

    Here we place the images in a horizontal stack with the direction `left-to-right.

    two images side by side with stack

    In this way, there is no columns to limit the number of pictures but we can only have one row. Thus, if we place too many images, they might be outside of the page.