Как вставить картинку в latex
Перейти к содержимому

Как вставить картинку в latex

  • автор:

Некоторые способы вставки PS-рисунков в L A T E X-документы

После того, как PS-файл с описанием рисунков готов, остается импортировать его в L A T E X-документ. В данном разделе приведено несколько примеров вставки PS-файла в L A T E X-документ.

С помощью команды \psboxto рисунок можно отмасштабировать и вставить в текущую строку. При этом просто задается требуемая ширина рисунка, а его размер по вертикали будет определен автоматически. Для того, чтобы эта команда работала, в приамбулу надо вставить \input .

Пример 1. Последовательность команд

\documentstyle \input \begin \begin \psboxto(5cm;0cm) \caption \end \begin $$\psboxto(5cm;5cm)$$ \end \end

вызовет вставку нашего рисунка в документ два раза. Оба раза рисунок будет одного и того же размера (с шириной по горизонтали, равной 5см). В первом случае он будет «прибит» к левому краю страницы, а подпись, сформированная с помощью \caption , расположится по центру. Второй раз, когда команда \psboxto оформлена с помощью $$ , сам рисунок тоже расположится по центру.

Команда \psfig , работающая при задании стилевой опции psfig , позволяет масштабировать рисунок в соответствии с заданной шириной и высотой.

Пример 2. Последовательность команд

\documentstyle[psfig] \begin \begin \psfig \end \end

вызовет вставку нашего рисунка, при этом он будет размером 5см x 5см и «прибит» к левому краю страницы. Оказалоь, однако, что эта команда может вступать в конфликт со стилями некоторых журналов (например, со стилем gandb ) .

Если требуется произвести масштабирование и по горизонтали, и по вертикали, можно воспользоваться командой \special , например, в виде
\special .

Масштабирование в команде \special задано в процентах. При этом надо иметь в виду, что по умолчанию единицей измерения в PostScript является 1 пункт, равный 1/72 дюйма (примерно 0.353мм). Поэтому в нашем примере, где размер поля был 640 x 350 (значение в заголовочном комментарии %%BoundingBox: 0 0 639 349 ) , ширина рисунка при значении hscale=100 окажется равной примерно 22.5cм.

Команду \special , как показывают следующие два примера, можно использовать по-разному.

Пример 3. Используется команда \makebox :

\documentstyle \begin \begin \centering \vspace \makebox[50mm][l]>% \makebox[12mm]<>% \makebox[50mm][l]> \makebox[62mm][c]\makebox[62mm][c] \caption \end \end

Здесь с помощью нашего PS-файла формируется рисунок, где рядом помещены две картинки одинаковой ширины и разной высоты, под ними стоят подписи ( a ) и ( b ) соответственно, и еще есть общая подпись под рисунком.

Пример 4. Вставка производится внутрь окружения picture (где началом координат по умолчанию считается левый нижний угол). Выполнение последовательности команд

\documentstyle \begin \begin \begin(375,275) \put(17,155)> \put(85,140)<\makebox<(a)>> \put(197,155)> \put(280,140)<\makebox<(b)>> \put(17,20)> \put(85,2)<\makebox<(c)>> \put(197,20)> \put(280,2)<\makebox<(d)>> \end \caption \end \end

приведет к формированию рисунка, на котором четыре раза повторяется одно и то же изображение, описанное в файле ex.ps, — две картинки рядом и ниже — еше раз две такие же картинки. Они подписаны буквами ( a ), ( b ), ( c ) и ( d ) соответственно, и имеется общая подпись под рисунком. Приведенный в этом примере способ импорта PS-файлов особенно удобен, если требуется наложить один рисунок на другой, т.к. конкретно указывается позиция, куда изображение должно быть вставлено.

Вставка изображений

Вставка изображений текст, как правило, доставляет некоторые трудности в связи с особенностями обработки оных в TeX’е.

Вставка изображений в варианте latex + dvips

При использовании связки latex + dvips (или latex + dvipdfm) картинки необходимо подготоваливать в .eps формате. Некоторые пакеты (например, R или Matlab) предоставляют возможность «родного» экспорта изображения в этот формат. В противном случае (например, для вставки скриншотов) можно использовать пакет Imagemagick.

Как только изображения подготовлены, то все просто. Подключаем в преамбуле пакет graphicx (больше никаких других пакетов не нужно!):

\usepackage

Если есть необходимость вставлять несколько изображений в одно, то еще subfigure:

\usepackage

. После этого в нужном месте достаточно вставить нечто типа:

\begin[h] \includegraphics[width=10cm] \caption \label \end

Расширение у файла указывать НЕ надо. Считается, что оно по-умолчанию .eps. В аргументах к команде \includegraphics можно указывать размер картинки и т.п. Более подробное описание пакета можно получить, скажем, здесь: PDF.

Вставка изображений в варианте pdflatex

pdflatex, в отличие от latex, не понимает формата eps. Все картинки надо готовить в форматах jpg, png или pdf (последний — предпочтительней). Произвести конверсию .eps ⇒ .pdf можно при помощи пакета Ghostscript (утилиты командной строки eps2pdf или меню «Export» в GhostView) или же уже известного пакета Imagemagick.

Все остальные инструкции по вставке изображений остаются в силе.

Inserting Images

Images are essential elements in most of the scientific documents. L a T e X provides several options to handle images and make them look exactly what you need. In this article we explain how to include images in the most common formats, how to shrink, enlarge and rotate them, and how to reference them within your document.

Contents

  • 1 Introduction
  • 2 The folder path to images
  • 3 Changing the image size and rotating the picture
  • 4 Positioning
    • 4.1 Wrapping text around figures
    • 5.1 Captions
    • 5.2 Labels and cross-references

    Introduction

    Below is an example on how to import a picture.

    \documentclassarticle> \usepackagegraphicx> \graphicspath ./images/> > \begindocument> The universe is immense and it seems to be homogeneous, in a large scale, everywhere we look at. \includegraphicsuniverse> There's a picture of a galaxy above \enddocument> 

    Example of inserting an image

    Latex can not manage images by itself, so we need to use the graphicx package. To use it, we include the following line in the preamble: \usepackage .

    The command \graphicspath < <./images/>> tells L a T e X that the images are kept in a folder named images under the directory of the main document.

    The \includegraphics command is the one that actually included the image in the document. Here universe is the name of the file containing the image without the extension, then universe.PNG becomes universe . The file name of the image should not contain white spaces nor multiple dots.

    Note: The file extension is allowed to be included, but it’s a good idea to omit it. If the file extension is omitted it will prompt LaTeX to search for all the supported formats. For more details see the section about generating high resolution and low resolution images.

    The folder path to images

    When working on a document which includes several images it’s possible to keep those images in one or more separated folders so that your project is more organised.

    The command \graphicspath < > tells L a T e X to look in the images folder. The path is relative to the current working directory—so, the compiler will look for the file in the same folder as the code where the image is included. The path to the folder is relative by default, if there is no initial directory specified, for instance

    %Path relative to the .tex file containing the \includegraphics command \graphicspath images/> > 

    This is a typically straightforward way to reach the graphics folder within a file tree, but can leads to complications when .tex files within folders are included in the main .tex file. Then, the compiler may end up looking for the images folder in the wrong place. Thus, it is best practice to specify the graphics path to be relative to the main .tex file, denoting the main .tex file directory as ./ , for instance:

    %Path relative to the main .tex file \graphicspath ./images/> > 

    as in the introduction.

    The path can also be absolute, if the exact location of the file on your system is specified. For example, if you were working on a local LaTeX installation on your own computer:

    %Path in Windows format: \graphicspath c:/user/images/> > %Path in Unix-like (Linux, Mac OS) format \graphicspath /home/user/images/> > 

    Notice that this command requires a trailing slash / and that the path is in between double braces.

    You can also set multiple paths if the images are saved in more than one folder. For instance, if there are two folders named images1 and images2 , use the command

    \graphicspath ./images1/>./images2/> > 

    Changing the image size and rotating the picture

    If we want to further specify how L a T e X should include our image in the document (length, height, etc), we can pass those settings in the following format:

    \begindocument> Overleaf is a great professional tool to edit online documents, share and backup your \LaTeX<> projects. Also offers a rather large help documentation. \includegraphics[scale=1.5]overleaf-logo> 

    Example of changing image size

    The command \includegraphics[scale=1.5] will include the image overleaf-logo in the document, the extra parameter scale=1.5 will do exactly that, scale the image 1.5 of its real size.

    You can also scale the image to a some specific width and height.

    \begindocument> Overleaf is a great professional tool to edit online documents, share and backup your \LaTeX<> projects. Also offers a rather large help documentation. \includegraphics[width=5cm, height=4cm]overleaf-logo> 

    Example of setting image height and width

    As you probably have guessed, the parameters inside the brackets [width=3cm, height=4cm] define the width and the height of the picture. You can use different units for these parameters. If only the width parameter is passed, the height will be scaled to keep the aspect ratio.

    The length units can also be relative to some elements in document. If you want, for instance, make a picture the same width as the text:

    \begindocument> The universe is immense and it seems to be homogeneous, in a large scale, everywhere we look at. \includegraphics[width=\textwidth]universe> 

    Example of image set to text width

    Instead of \textwidth you can use any other default L a T e X length: \columnsep , \linewidth , \textheight , \paperheight , etc. See the reference guide for a further description of these units.

    There is another common option when including a picture within your document, to rotate it. This can easily accomplished in L a T e X :

    \begindocument> Overleaf is a great professional tool to edit online, share and backup your \LaTeX<> projects. Also offers a rather large base of help documentation. \includegraphics[scale=1.2, angle=45]overleaf-logo> 

    Example of rotating an image

    The parameter angle=45 rotates the picture 45 degrees counter-clockwise. To rotate the picture clockwise use a negative number.

    Positioning

    In the previous section was explained how to include images in your document, but the combination of text and images may not look as we expected. To change this we need to introduce a new environment.

    In the next example the figure will be positioned right below this sentence. \beginfigure>[h] \includegraphics[width=8cm]Plot> \endfigure> 

    Example of positioning figures

    The figure environment is used to display pictures as floating elements within the document. This means you include the picture inside the figure environment and you don’t have to worry about it’s placement, L a T e X will position it in a such way that it fits the flow of the document.

    Anyway, sometimes we need to have more control on the way the figures are displayed. An additional parameter can be passed to determine the figure positioning. In the example, begin[h] , the parameter inside the brackets set the position of the figure to here. Below a table to list the possible positioning values.

    Parameter Position
    h Place the float here, i.e., approximately at the same point it occurs in the source text (however, not exactly at the spot)
    t Position at the top of the page.
    b Position at the bottom of the page.
    p Put on a special page for floats only.
    ! Override internal parameters LaTeX uses for determining «good» float positions.
    H Places the float at precisely the location in the L a T e X code. Requires the float package, though may cause problems occasionally. This is somewhat equivalent to h!.

    In the next example you can see a picture at the t op of the document, despite being declared below the text.

    In this picture you can see a bar graph that shows the results of a survey which involved some important data studied as time passed. \beginfigure>[t] \includegraphics[width=8cm]Plot> \centering \endfigure> 

    Example of bar graph

    The additional command \centering will centre the picture. The default alignment is left.

    Wrapping text around figures

    It’s also possible to wrap the text around a figure. When the document contains small pictures this makes it look better.

    \beginwrapfigure>r>0.25\textwidth> %this figure will be at the right \centering \includegraphics[width=0.25\textwidth]mesh> \endwrapfigure> There are several ways to plot a function of two variables, depending on the information you are interested in. For instance, if you want to see the mesh of a function so it easier to see the derivative you can use a plot like the one on the left. \beginwrapfigure>l>0.25\textwidth> \centering \includegraphics[width=0.25\textwidth]contour> \endwrapfigure> On the other side, if you are only interested on certain values you can use the contour plot, you can use the contour plot, you can use the contour plot, you can use the contour plot, you can use the contour plot, you can use the contour plot, you can use the contour plot, like the one on the left. On the other side, if you are only interested on certain values you can use the contour plot, you can use the contour plot, you can use the contour plot, you can use the contour plot, you can use the contour plot, you can use the contour plot, you can use the contour plot, like the one on the left.

    Example of plot

    For the commands in the example to work, you have to import the wrapfig package. To use wrapfig , include the following line in the document preamble:

    \usepackagewrapfig> 

    This makes the wrapfigure environment available and we can place an \includegraphics command inside it to create a figure around which text will be wrapped. Here is how we can specify a wrapfigure environment:

    \beginwrapfigure>[lineheight]position>width> . \endwrapfigure> 

    The position parameter has eight possible values:

    r R right side of the text
    l L left side of the text
    i I inside edge–near the binding (in a twoside document)
    o O outside edge–far from the binding

    The uppercase version allows the figure to float. The lowercase version means exactly here.

    Now you can define the wrapfigure environment by means of the commands \begin \end . Notice that the environment has two additional parameters enclosed in braces. Below the code is explained with more detail:

    This defines the alignment of the figure. Set l for left and r for right. Furthermore, if you are using a book or any similar format, use instead o for the outer edge and i for the inner edge of the page. This is the width of figure box. It’s not the width of the image itself, that must be set in the \includegraphics command. Notice that the length is relative to the text width, but normal units can also be used (cm, in, mm, etc). See the reference guide for a list of units. \centering This was already explained, but in this example the image will be centred by using its container as reference, instead of the whole text.

    For a more complete article about image positioning see Positioning images and tables

    Captioning, labelling and referencing

    Captioning images to add a brief description and labelling them for further reference are two important tools when working on a lengthy text.

    Captions

    Let’s start with a caption example:

    \beginfigure>[h] \captionExample of a parametric plot ($\sin (x), \cos(x), x$)> \centering \includegraphics[width=0.5\textwidth]spiral> \endfigure> 

    Example of parametric plot

    It’s really easy, just add the \caption and inside the braces write the text to be shown. The placement of the caption depends on where you place the command; if it’s above the \includegraphics then the caption will be on top of it, if it’s below then the caption will also be set below the figure.

    Captions can also be placed right after the figures. The sidecap package uses similar code to the one in the previous example to accomplish this.

    \documentclassarticle> \usepackage[rightcaption]sidecap> \usepackagegraphicx> %package to manage images \graphicspath images/> > \beginSCfigure>[0.5][h] \captionUsing again the picture of the universe. This caption will be on the right> \includegraphics[width=0.6\textwidth]universe> \endSCfigure> 

    Example of parametric plot with caption

    There are two new commands

    \usepackage[rightcaption] As you may expect this line will import a package named sidecap , but there is an additional parameter: rightcaption . This parameter establishes the placement of the caption at the right of the picture, you can also use leftcaption . In book-like documents outercaption and innercaption are also available. The names of these are self-descriptive. \begin[0.5][h] \end Defines an environment similar to figure . The first parameter is the width of the caption relative to the size of the image, as declared in \includegraphics . The second parameter h works exactly as in the figure environment. See the placement section for more information.

    You can do a more advanced management of the caption formatting. Check the further reading section for references.

    Labels and cross-references

    Figures, just as many other elements in a L a T e X document (equations, tables, plots, etc) can be referenced within the text. This is very easy, just add a \label to the figure or SCfigure environment, then later use that label to refer the picture.

    \beginfigure>[h] \centering \includegraphics[width=0.25\textwidth]mesh> \captiona nice plot> \labelfig:mesh1> \endfigure> As you can see in the figure \reffig:mesh1>, the function grows near 0. Also, in the page \pagereffig:mesh1> is the same example.

    Example of figure with label

    There are three commands that generate cross-references in this example.

    \label This will set a label for this figure. Since labels can be used in several types of elements within the document, it’s a good practice to use a prefix, such as fig: in the example. \ref This command will insert the number assigned to the figure. It’s automatically generated and will be updated if insert some other figure before the referenced one. \pageref This prints out the page number where the referenced image appears.

    The \caption is mandatory to reference a figure.

    Another great characteristic in a L a T e X document is the ability to automatically generate a list of figures. This is straightforward.

    \listoffigures 

    Example of list of figures

    This command only works on captioned figures, since it uses the caption in the table. The example above lists the images in this article.

    Important Note: When using cross-references your L a T e X project must be compiled twice, otherwise the references, the page references and the table of figures won’t work—Overleaf takes care of that for you.

    Generating high-res and low-res images

    So far while specifying the image file name in the \includegraphics command we have omitted file extensions. However, that is not necessary, though it is often useful. If the file extension is omitted, LaTeX will search for any supported image format in that directory, and will search for various extensions in the default order (which can be modified).

    This is useful in switching between development and production environments. In a development environment (when the article/report/book is still in progress), it is desirable to use low-resolution versions of images (typically in .png format) for fast compilation of the preview. In the production environment (when the final version of the article/report/book is produced), it is desirable to include the high-resolution version of the images.

    This is accomplished by

    • Not specifying the file extension in the \includegraphics command, and
    • Specifying the desired extension in the preamble.

    Thus, if we have two versions of an image, venndiagram.pdf (high-resolution) and venndiagram.png (low-resolution), then we can include the following line in the preamble to use the .png version while developing the report —

    \DeclareGraphicsExtensions.png,.pdf> 

    The command above will ensure that if two files are encountered with the same base name but different extensions (for example venndiagram.pdf and venndiagram.png), then the .png version will be used first, and in its absence the .pdf version will be used, this is also a good ideas if some low-resolution versions are not available.

    Once the report has been developed, to use the high-resolution .pdf version, we can change the line in the preamble specifying the extension search order to

    \DeclareGraphicsExtensions.pdf,.png> 

    Improving on the technique described in the previous paragraphs, we can also instruct L a T e X to generate low-resolution .png versions of images on the fly while compiling the document if there is a PDF that has not been converted to PNG yet. To achieve that, we can include the following in the preamble after \usepackage

    \usepackageepstopdf> \epstopdfDeclareGraphicsRule.pdf>png>.png>convert #1 \OutputFile> \DeclareGraphicsExtensions.png,.pdf> 

    If venndiagram2.pdf exists but not venndiagram2.png, the file venndiagram2-pdf-converted-to.png will be created and loaded in its place. The command convert #1 is responsible for the conversion and additional parameters may be passed between convert and #1. For example — convert -density 100 #1.

    There are some important things to have in mind though:

    • For the automatic conversion to work, we need to call pdflatex with the —shell-escape option.
    • For the final production version, we must comment out the \epstopdfDeclareGraphicsRule , so that only high-resolution PDF files are loaded. We’ll also need to change the order of precedence.

    Reference guide

    L a T e X units and legths

    Abbreviation Definition
    pt A point, is the default length unit. About 0.3515mm
    mm a millimetre
    cm a centimetre
    in an inch
    ex the height of an x in the current font
    em the width of an m in the current font
    \columnsep distance between columns
    \columnwidth width of the column
    \linewidth width of the line in the current environment
    \paperwidth width of the page
    \paperheight height of the page
    \textwidth width of the text
    \textheight height of the text
    \unitlength units of length in the picture environment.

    About image types in L a T e X

    latex When compiling with latex, we can only use EPS images, which is a vector format. pdflatex If we are compiling using «pdflatex» to produce a PDF, then we can use a number of image formats —

    JPG: Best choice if we want to insert photos PNG: Best choice if we want to insert diagrams (if a vector version could not be generated) and screenshots PDF: Even though we are used to seeing PDF documents, a PDF can also store images EPS: EPS images can be included using the epstopdf package (we just need to install the package, we don't need to use \usepackage<> to include it in our document.)

    Vector format or bitmap format? Images can be of either vector format of bitmap format. Generally we don’t need to worry about it, but if we do happen to know the format the image is in, we can use that information to choose an appropriate image format to include in our LaTeX document. If we have an image in vector format, we should go for PDF or EPS. If we have it in bitmap format, we should go for JPG or PNG, as storing bitmap pictures in PDF or EPS takes a lot of disk space.

    Further reading

    For more information see

    • Positioning images and tables
    • Lists of tables and figures
    • Single sided and double sided documents
    • Lengths in LaTeX
    • floatrow package for advanced caption managing of floating elements (tables and figures)
    • sidecap package documentation, for side-figure captions
    • epstopdf package documentation (EPS to PDF conversion)

    Записки дебианщика

    В этом блоге публикуются заметки и решения, найденные в процессе работы, освоения и жизни в дистрибутиве Debian GNU/Linux.

    12/15/2008

    Иллюстрации и рисунки в LaTeX

    Этот пост является частью большой статьи
    «Как оформить диплом в LaTeX?»,
    которую написал virens,
    ведущий блога «Записки дебианщика».

    Здесь приводятся базовые идеи и примеры, которые вам нужно освоить для вставки изображений и рисунков в LaTeX. Мы рассмотрим вставку нескольких рисунков в ряд и оформление групп рисунков, для чего будем пользоваться окружением minipage. Для набора дипломов по техническим специальностям приведённых сведений должно хватить.

    Подготовка
    Для начала работы с изображениями нужно подключить пакет graphicx, который обеспечивает их вставку в текст документа. Есть много драйверов для работы с изображениями, но мы будем использовать dvips — это позволит нам потом сравнительно легко и довольно просто конвертировать диплом из LaTeX в Word или OpenOffice через формат RTF, используя открытую программу latex2rtf. Для этого ваши рисунки нужно конвертировать в EPS, что делается программой convert из пакета imagemagick или утилитой sam2p. И imagemagick, и sam2p есть в стандартных репозиториях Debian и ставятся на раз.

    Как вставить в LaTeX-документ изображение?
    Рисунок в технической статье или отчёте — это не просто картинка, а ещё и подпись к нему, и возможность поставить на рисунок ссылку. Для этого сначала в преамбуле документа (это те самые магические заклинания, которые до \begin < document >) нужно вставить следующее:

    Рисунки лучше хранить в отдельных каталогах, идеально — для каждой главы диплома свой каталог. Следует перечислить все каталоги с рисунками, чтобы ЛаТеХ смог их найти. Делается это так:

    \graphicspath >

    В ЛаТеХе вы только упоминаете рисунок — ставите на него относительную ссылку при помощи команды
    \includegraphics [width=1 \linewidth ]

    Как уже говорилось, если ваш рисунок в формате PNG/TIF/JPG или ещё каком-нибудь, нужно сначала перевести его в EPS при помощи программы convert из пакета imagemagick или утилитой sam2p. Например, чтобы конвертировать файл в EPS программой convert, нужно дать команду:

    convert image.jpg image.eps

    После этого копируем полученный eps-файл в каталог, указанный в \graphicspath <>, в данном случае подкаталог noiseimages, который находится в каталоге с нашим tex-файлом.

  • определить место рисунка в тексте — разрешить алгоритмам ТеХа принять решение исходя из заполненности страницы \begin < figure >[h] «хотелось бы картинку здесь», настойчиво просить разместить после текста \begin < figure >[h!] «очень хочу картинку здесь», и ударить кулаком по столу — картинку тут и точка \begin < figure >[H] «ХОЧУ картинку здесь и баста», а с прибавлением буквы p мы заставляем поместить ЛаТеХ картинку отдельно на страницу так: \begin < figure >[pH].
  • задать размер изображения в относительных единицах — долях от ширины строки или текста
  • вставить подпись под рисунком \caption
  • вставить ссылку на рисунок \label
  • Результат в документе:

    Всё просто и понятно в этом примере: мы разместили рисунок, который находится в файле image, в тексте — оставляем выбор размещения за ТеХом. Размер его будет во всю строку, подпись — «Рис.N:Зависимость сигнала от шума для данных.», где N — номер рисунка, который будет вставлен позже, во время сборки документа. Расширение у документа не указывается: если вы используете драйвер dvips, то это обязательно postscipt.

    Теперь надо ссылаться на рисунок так: как показано на Рис.~ \ref < ris:image >— так вы всегда сошлётесь на правильный рисунок. Только нужно следить, чтобы имена рисунков не повторялись. Главное — делать название рисунков осмысленными и понятными вам, а не просто ris1, ris2. Естественно, что LaTeX — это язык программирования, так что все советы по грамотному написанию программ уместны и здесь.
    Маленькая хитрость: команду \caption <> нужно использовать обязательно перед \label < >, иначе в документе ссылка будет не на рисунок, а на текущую subsection.

    Полезно запомнить, что ЛаТеХ рассматривает рисунок как одну большую букву. Поэтому в некоторых сложных случаях полезно применять грубую силу, т.е. например можно сделать интервал от подписи командой \vspace — не очень изящно, зато действенно.

    Два рисунка в строчку
    Немного усложним пример — вставим два рисунка в строку, с единой подписью под каждым. Можно вставить ещё один \includegraphics , но под рисунками должны быть подписи а) и б) и нужно, чтобы они были по центру. Для этого есть замечательное окружение \begin < minipage >.. \end < minipage >. То есть резервируем место под рисунок, и вставляем его во фрейм. Вот так:

    Здесь ширина рисунка указана 1 \linewidth то есть во всю строку, но строка теперь ширины 0.49 \linewidth так что рисунок будет во весь фрейм размера в половину строки. Кроме того, после каждого рисунка идётразрыв строки и буква, обозначающая рисунок. Нужно помнить, что ссылка и подпись под рисунками одна.

    Результат, как всегда, логичен и приятен:

    Команда \hfill позволяет раздвинуть рисунки к краям страницы, как бы заполняя между ними пространство пустотой. Из приведённых примеров должно быть понятно, как вставлять несколько рисунков в строку, теперь немного усложним задачу и попробуем вставить два рисунка в строчку и два в столбец.

    Два рисунка в строчку и два в столбец
    Следующий уровень — вставляем рисунки не только в строчку, но и по столбцам. Идея таже, только после заполнения строчек вставляем команду \vfill которая растолкнёт рисунки по строкам. Всё остальное остаётся в силе: используем окружение minipage и грамотно выставляем ширину этих самых minipage так, чтобы оставался небольшой зазор: для двух картинок 0.48, для трёх 0.31 и так далее. Собственно, код:

    То есть теперь мы не падаем в обморок от просьбы вставить 12 рисунков по 3 в ряд. Все идеи те же самые, хотя едва ли в дипломе вам придётся столкнуться с большим количеством хитро расположенных рисунков.


    Два рисунка с разными подписями

    Это важный частный случай, так как довольно часто сделать одну подпись для двух рисунков или длинно, или сложно, и поэтому лучше выделить их в два отдельных рисунка, но в ряд. Мы не будем привлекать для этого отдельные сущности, а воспользуемся старым-добрым minipage. Надеюсь, благодарный читатель ещё помнит, что ЛаТеХ — он как рельса, прост и бесхитростен, и делает то, что вы ему прикажете, как бы костыляво это не выглядело:

    Для этого случая код следующий:

    Как видно, всё достаточно легко и просто. Не забываем проставлять нужные размеры minipage и рисунков, периодически посматривая на результат в kdvi и корректируя код по ходу дела.


    Три рисунка с индивидуальными ссылками

    Вариация на тему предыдущего случая, но через subfigure. При этом можно ссылаться на под-рисунки отдельными ссылками, например «см. Рис ~\ref fig:actuatorscouplingSheme _ decoupledcase > будет отображено как «Рис 2(а)». Добавляем в преамбулу:

    \usepackage < subfigure >

    и далее вставляем этот код:

    Так что теперь в тексте можем ссылаться отдельно на рисунок 2а, 2b или 2c с помощью команды \ref <>. На самом деле, subfigures умеют намного больше.

    Три рисунка разной высоты
    Иногда случается такая партизанская засада, как разномасштабные рисунки, которые под один размер подгонять нехорошо по смыслу, и нужно сделать так, чтобы подписи к ним были в одну строчку. Иначе получается некрасиво: буквы под рисунками в разных положениях. Я не претендую на истину в последней инстанции, но вот выход, который я нашёл для себя:

    Как это выглядит в документе:

    Здесь игра в том, что после всех окружений minipage, в которых вставлены картинки, идёт отдельная minipage. В ней — таблица, ширина колонок которой точно такая же, как и ширина minipage для картинок. Вот, собственно, код:

    Я немного забегаю вперёд и использую таблицы, которые будут описываться в другом разделе, но думаю, что человек с высшим образованием без труда переведёт слово tabular.

    Рисунок с обтеканием текста в LaTeX
    В дипломах такие фокусы не приветствуются, но если очень нужно — делается сравнительно просто пакетом расширения wrapfig. Для это подключаем этот пакет в преамбуле \usepackage .

    После этого у нас появляется замечательная возможность продемонстрировать свою невероятную оформительскую крутизну, используя окружение \begin < wrapfigure >. \end < wrapfigure >, когда нужно сделать обтекание рисунка:

    \begin < wrapfigure >[16]
    \vspace
    \includegraphics [width= \linewidth ]
    \caption
    \label < fig:somelabel >
    \end < wrapfigure >

    Подсвеченные параметры означают:

    [16] — определяет высоту рисунка в число строк текста и позволяет отбить дополнительное место для рисунков.

    — положение картинки на странице, можно слева или справа .
    — ширина картинки в относительных единицах от ширины линии.

    Тонкий момент: на самом деле, параметр положения рисунка на странице можно писать с маленькой буквы (слева или справа ), но это заставляет ЛаТеХ поместить изображение именно там, где вы прикажете. Если же ставить большие буквы (слева или справа ), то это даст больше свободы ЛаТеХу.

    Ещё тонкость в том, что автоматика может сделать слишком много (или мало) места в верхней или нижней части обтекаемого рисунка. Вот тут нам поможет дополнительный аргумент [lineheight] , который в данном примере задан как [16]. Он-то определяет высоту рисунка в строках текста. Другой возможностью является добавление или удаления промежутков с помощью команды \vspace и данном примере \vspace ЛаТеХу приказывается сместить картинку немного вверх, чтобы выиграть место для текста.


    Сквозная нумерация рисунков в LaTeX

    Часто требуется, чтобы номер рисунка содержал в себе номер главы (вроде Рис. 1.1) . Чтобы была сделана нумерация по главам, достаточно изменить счётчик рисунков в преамбуле документа вот так:

    \renewcommand < \thefigure >< \thechapter . \arabic >

    • \arabic 4
    • \roman iv
    • \Roman IV
    • \alph d
    • \Alph D

    Выводы

    Вставка изображений в ЛаТеХ — дело очень простое, и оно сэкономит вам много нервных клеток для более важных дел. Важно то, что со временем эти конструкции у вас войдут в привычку, и однажды написанный код начнёт кочевать из работы в работу.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *