LaTeX/Creating Graphics
In the previous chapter, you learned that you can import or link graphics into LaTeX, such as graphics that you have created in another program or obtained elsewhere. In this chapter, you will learn how to create or embed graphics directly in a LaTeX document. The graphics is marked up using commands similar to those for typesetting bold text or creating mathematical formulas, as the following example of embedded graphics shows:
\begin{displaymath} \xymatrix{ \bullet \ar[r] \ar@{.>}[r] & \bullet } \end{displaymath}
There are several packages supporting the creation of graphics directly in LaTeX, including picture, xy-Pic, and PGF/TikZ, described in the following sections.
Contents |
[edit] Overview
The picture environment allows programming pictures directly in LaTeX. On the one hand, there are rather severe constraints, as the slopes of line segments as well as the radii of circles are restricted to a narrow choice of values. On the other hand, the picture environment of LaTeX2e brings with it the \qbezier command, "q" meaning quadratic. Many frequently-used curves such as circles, ellipses, and catenaries can be satisfactorily approximated by quadratic Bézier curves, although this may require some mathematical toil. If a programming language like Java is used to generate \qbezier blocks of LaTeX input files, the picture environment becomes quite powerful.
Although programming pictures directly in LaTeX is severely restricted, and often rather tiresome, there are still reasons for doing so. The documents thus produced are "small" with respect to bytes, and there are no additional graphics files to be dragged along.
Packages like epic, eepic or pstricks enhance the original picture environment, and greatly strengthen the graphical power of LaTeX.
While the former two packages just enhance the picture environment, the pstricks package has its own drawing environment, pspicture. The power of pstricks stems from the fact that this package makes extensive use of PostScript possibilities. Unfortunately it has one big shortcoming: it doesn't work together with pdfLaTeX, as such to generate a PDF document form TeX source you have to go TeX→DVI→PDF; losing hyperlinks, metadata and microtypographic features of pdflatex. In addition, numerous packages have been written for specific purposes. One of them is XY-pic, described at the end of this chapter. A wide variety of these packages is described in detail in The LaTeX Graphics Companion (not to be confused with The LaTeX Companion).
Perhaps the most powerful graphical tool related with LaTeX is MetaPost, the twin of Donald E. Knuth’s METAFONT. MetaPost has the very powerful and mathematically sophisticated programming language of METAFONT. Contrary to METAFONT, which generates bitmaps, MetaPost generates encapsulated PostScript files, which can be imported in LaTeX. For an introduction, see A User’s Manual for MetaPost. A very thorough discussion of LaTeX and TEX strategies for graphics (and fonts) can be found in TEX Unbound.
The last but certainly not least is the PGF/TikZ system. While the previous systems (picture, epic, pstricks or metapost) focus on the how to draw, TikZ focuses more on the what to draw. One could say that TikZ is to drawing in LaTeX as LaTeX is to digital typesetting. It's recommended to use it if your LaTeX distribution includes it.
[edit] The picture Environment
[edit] Basic Commands
A picture environment is available in any LaTeX distribution, without the need of loading any external package. This environment is created with one of the two commands
\begin{picture}(x, y) ... \end{picture}
or
\begin{picture}(x, y)(x0, y0) ... \end{picture}
The numbers x, y, x0, y0 are numbers (lengths) in the units of \unitlength, which can be reset any time (but not within a picture environment) with a command such as
\setlength{\unitlength}{1.2cm}
The default value of \unitlength is 1pt. The first pair, (x,y), affects the reservation, within the document, of rectangular space for the picture. The optional second pair, (x0,y0), assigns arbitrary coordinates to the bottom left corner of the reserved rectangle.
Most drawing commands have one of the two forms
\put(x, y){object}
or
\multiput(x, y)(dx, dy){n}{object}
Bézier curves are an exception. They are drawn with the command
\qbezier(x1, y1)(x2, y2)(x3, y3)
[edit] Line Segments
Line segments are drawn with the command:
\put(x, y){\line(x1, y1){length}}
The \line command has two arguments:
- a direction vector,
- a "length" (sort of: this argument is the length of the vertical coordinate in the case of a vertical line segment and of the horizontal coordinate in all other cases, rather than the length of the segment itself).
The components of the direction vector are restricted to the integers (−6, −5, ... , 5, 6) and they have to be coprime (no common divisor except 1). The figure below illustrates all 25 possible slope values in the first quadrant. The length is relative to \unitlength.
[edit] Arrows
Arrows are drawn with the command
\put(x, y){\vector(x1, y1){length}}
For arrows, the components of the direction vector are even more narrowly restricted than for line segments, namely to the integers (−4, −3, ... , 3, 4). Components also have to be coprime (no common divisor except 1). Notice the effect of the \thicklines command on the two arrows pointing to the upper left.
[edit] Circles
The command
\put(x, y){\circle{diameter}}
draws a circle with center (x, y) and diameter (not radius) specified by diameter. The picture environment only admits diameters up to approximately 14mm, and even below this limit, not all diameters are possible. The \circle* command produces disks (filled circles). As in the case of line segments, one may have to resort to additional packages, such as eepic or pstricks.
There is another possibility within the picture environment. If one is not afraid of doing the necessary calculations (or leaving them to a program), arbitrary circles and ellipses can be patched together from quadratic Bézier curves. See Graphics in LaTeX2e for examples and Java source files.
[edit] Text and formulas
As this example shows, text and formulas can be written in the environment with the \put command in the usual way:
[edit] \multiput and \linethickness
The command
\multiput(x, y)(dx, dy ){n}{object}
has 4 arguments: the starting point, the translation vector from one object to the next, the number of objects, and the object to be drawn. The \linethickness command applies to horizontal and vertical line segments, but neither to oblique line segments, nor to circles. It does, however, apply to quadratic Bézier curves!
[edit] Ovals
The command
\put(x, y){\oval(w, h)}
or
\put(x, y){\oval(w, h)[position]}
produces an oval centered at (x, y) and having width w and height h. The optional position arguments b, t, l, r refer to "top", "bottom", "left", "right", and can be combined, as the example illustrates. Line thickness can be controlled by two kinds of commands: \linethickness{length} on the one hand, \thinlines and \thicklines on the other. While \linethickness{length} applies only to horizontal and vertical lines (and quadratic Bézier curves), \thinlines and \thicklines apply to oblique line segments as well as to circles and ovals.
[edit] Multiple Use of Predefined Picture Boxes
A picture box can be declared by the command
\newsavebox{name}
then defined by
\savebox{name}(width,height)[position]{content}
and finally arbitrarily often be drawn by
\put(x, y){\usebox{name}}
The optional position parameter has the effect of defining the "anchor point" of the savebox. In the example it is set to "bl" which puts the anchor point into the bottom left corner of the savebox. The other position specifiers are top and right.
The name argument refers to a LaTeX storage bin and therefore is of a command nature (which accounts for the backslashes in the current example). Boxed pictures can be nested: In this example, \foldera is used within the definition of \folderb. The \oval command had to be used as the \line command does not work if the segment length is less than about 3 mm.
[edit] Quadratic Bézier Curves
The command
\qbezier(x1, y1)(x, y)(x2, y2)
draws a quadratic bezier curve where P1 = (x1,y1), P2 = (x2,y2) denote the end points, and S = (x,y) denotes the intermediate control point. The respective tangent slopes, m1 and m2, can be obtained from the equations
See Graphics in LaTeX2e for a Java program which generates the necessary \qbezier command line.
As this example illustrates, splitting up a circle into 4 quadratic Bézier curves is not satisfactory. At least 8 are needed. The figure again shows the effect of the \linethickness command on horizontal or vertical lines, and of the \thinlines and the \thicklines commands on oblique line segments. It also shows that both kinds of commands affect quadratic Bézier curves, each command overriding all previous ones.
[edit] Catenary
In this figure, each symmetric half of the catenary y = cosh x − 1 is approximated by a quadratic Bézier curve. The right half of the curve ends in the point (2, 2.7622), the slope there having the value m = 3.6269. Using again equation (*), we can calculate the intermediate control points. They turn out to be (1.2384, 0) and (−1.2384, 0). The crosses indicate points of the real catenary. The error is barely noticeable, being less than one percent. This example points out the use of the optional argument of the \begin{picture} command. The picture is defined in convenient "mathematical" coordinates, whereas by the command
\begin{picture}(4.3,3.6)(-2.5,-0.25)
its lower left corner (marked by the black disk) is assigned the coordinates (−2.5,−0.25).
[edit] Plotting graphs
The control points of the two Bézier curves were calculated with formulas (*). The positive branch is determined by P1 = (0,0), m1 = 1 and P2 = (2,tanh 2), m2 = 1 / cosh 22. Again, the picture is defined in mathematically convenient coordinates, and the lower left corner is assigned the mathematical coordinates (−3,−2) (black disk).
[edit] The picture environment and gnuplot
The powerful scientific plotting package gnuplot has the capability to output directly to a LaTeX picture environment. It is often far more convenient to plot directly to LaTeX, since this saves having to deal with potentially troublesome postscript files. Plotting scientific data (or, indeed, mathematical figures) this way gives much greater control, and of course typesetting ability, than is available from other means (such as postscript). Such pictures can then be added to a document by an \include{} command.
N.B. gnuplot is a powerful piece of software with a vast array of commands. A full discussion of gnuplot lies beyond the scope of this note.
[edit] Xy-pic
xy is a special package for drawing diagrams. To use it, simply add the following line to the preamble of your document:
\usepackage[all]{xy}
where "all" means you want to load a large standard set of functions from Xy-pic, suitable for developing the kind of diagrams discussed here.
The primary way to draw Xy-pic diagrams is over a matrix-oriented canvas, where each diagram element is placed in a matrix slot:
\begin{displaymath} \xymatrix{A & B \\ C & D } \end{displaymath} |
The \xymatrix command must be used in math mode. Here, we specified two lines and two columns. To make this matrix a diagram we just add directed arrows using the \ar command.
\begin{displaymath} \xymatrix{ A \ar[r] & B \ar[d] \\ D \ar[u] & C \ar[l] } \end{displaymath} |
The arrow command is placed on the origin cell for the arrow. The arguments are the direction the arrow should point to (up, down, right and left).
\begin{displaymath} \xymatrix{ A \ar[d] \ar[dr] \ar[r] & B \\ D & C } \end{displaymath} |
To make diagonals, just use more than one direction. In fact, you can repeat directions to make bigger arrows.
\begin{displaymath} \xymatrix{ A \ar[d] \ar[dr] \ar[drr] & & \\ B & C & D } \end{displaymath} |
We can draw even more interesting diagrams by adding labels to the arrows. To do this, we use the common superscript and subscript operators.
\begin{displaymath} \xymatrix{ A \ar[r]^f \ar[d]_g & B \ar[d]^{g'} \\ D \ar[r]_{f'} & C } \end{displaymath} |
As shown, you use these operators as in math mode. The only difference is that that superscript means "on top of the arrow", and subscript means "under the arrow". There is a third operator, the vertical bar: | It causes text to be placed in the arrow.
\begin{displaymath} \xymatrix{ A \ar[r]|f \ar[d]|g & B \ar[d]|{g'} \\ D \ar[r]|{f'} & C } \end{displaymath} |
To draw an arrow with a hole in it, use \ar[...]|\hole. In some situations, it is important to distinguish between different types of arrows. This can be done by putting labels on them, or changing their appearance
Notice the difference between the following two diagrams:
\begin{displaymath} \xymatrix{ \bullet \ar[r] \ar@{.>}[r] & \bullet } \end{displaymath} |
|
\begin{displaymath} \xymatrix{ \bullet \ar@/^/[r] \ar@/_/@{.>}[r] & \bullet } \end{displaymath} |
The modifiers between the slashes define how the curves are drawn. Xy-pic offers many ways to influence the drawing of curves; for more information, check the Xy-pic documentation.
If you are interested in a more thorough introduction then consult the Xy-pic Home Page, which contains links to several other tutorials as well as the reference documentation.
[edit] PGF/TikZ
One possible solution how to draw graphics directly with TeX commands is PGF/TikZ. TikZ can produce portable graphics in both PDF and PostScript formats using either plain (pdf)TEX, (pdf)Latex or ConTEXt. It comes with very good documentation and an extensive collection of examples: http://www.texample.net/tikz/
PGF ("portable graphics format") is the basic layer, providing a set of basic commands for producing graphics, and TikZ ("TikZ ist kein Zeichenprogramm") is the frontend layer with a special syntax, making the use of PGF easier. TikZ commands are prevalently similar to Metafont, the option mechanism is similar to PsTricks syntax.
Other packages building on top of TikZ (e.g., for drawing electrical circuits) can be found here: http://ftp.dante.de/tex-archive/help/Catalogue/bytopic.html#pgftikzsection
In the following some basics of TikZ are presented.
[edit] Loading Package, Libraries - tikzpicture environment
Using TikZ in a LaTeX document requires loading the tikz package:
\usepackage{tikz}
somewhere in the preamble. This will automatically load the pgf package. To load further libraries use
\usetikzlibrary{⟨list of libraries separated by commas⟩}
Examples for libraries are "arrows", "automata", "backgrounds", "calendar", "chains", "matrix", "mindmap", "patterns", "petri", "shadows", "shapes.geometric", "shapes.misc", "spy", "trees".
Drawing commands have to be enclosed in an tikzpicture environment
\begin{tikzpicture}[⟨options ⟩] ⟨tikz commands⟩ \end{tikzpicture}
or alternatively
\tikz[⟨options⟩]{⟨tikz commands⟩}
One possible option useful for inlined graphics is
baseline=⟨dimension⟩
Without that option the lower end of the picture is put on the baseline of the surrounding text. Using this option, you can specify that the picture should be raised or lowered such that the height ⟨dimension⟩ is on the baseline.
Another option to scale the entire picture is
scale=⟨factor⟩
[edit] Specifying Coordinates
Coordinates are specified in round brackets in an arbitrary TEX dimension either using cartesian coordinates (comma separated), e.g. 1cm in x and 2pt in y direction
(1cm,2pt)
or using polar coordinates (colon separated), e.g. 1cm in 30 degree direction
(30:1cm)
Without specifying a unit (1,2), the standard one is cm (1cm,2cm).
Relative coordinates to the previous given point are given by adding one or two plus signs in front of the coordinate. With "++" the last point of the path becomes the current position, with "+" the previous point stays the current path position. Example: 2 standard units to the right of the last point used:
++(2,0)
[edit] Syntax for Paths
A path is a series of straight and curved line segments. It has to end with a semicolon.
\path[<options>]⟨specification⟩;
Options for path actions are e.g: "draw", "fill", "pattern", "shade" (filling, in which its color changes smoothly from one to another), "clip" (all subsequent drawings up to the end of the current scope are clipped against the current path and the size of subsequent paths will not be important for the picture size), "use as bounding box".
The "\path" command with these options can be combined to: "\draw", "\fill", "\filldraw", "\pattern", "\shade", "\shadedraw", "\clip", "\useasboundingbox" .
Geometric path options: "rotation=<angle in degree>", "xshift=<length>", "yshift=<length>", "scaling=<factor>", "xscale=<factor>", "yscale=<factor>".
Color options for drawing paths: "color=<color name>", "draw=<line color>", "opacity=<factor>".
Line width options: "line width=<dimension>", and abbreviations "ultra thin" for 0.1pt, "very thin" for 0.2pt, "thin" for 0.4pt (the default width), "semithick" for 0.6pt, "thick" for 0.8pt, "very thick" for 1.2pt, "ultra thick" for 1.6pt.
Line end, line join options: "line cap=<type: round, rect, or butt>", "arrows=<start arrow kind>-<end arrow kind>", "rounded corners", "rounded corners=<size>", "line join=<type: round, bevel, or miter>".
Line pattern options: "dash pattern=<dash pattern>" (e.g. "dash pattern=on 2pt off 3pt on 4pt off 4pt"), "dash phase=⟨dash phase⟩", "solid", "dashed", "dotted", "dashdotted", "densely dotted", "loosely dotted", "double".
Options for filling paths are e.g. "fill=<fill color>", "pattern=<name>", "pattern color=<color>"
Straight lines are given by coordinates separated by a double minus,
\draw (1,0) -- (0,0) -- (0,1);
The first coordinate represents a move-to operation. This is followed by a series of “path extension operations”, like "-- (coordinates)".
A further move-to operation in an existing path starts a new part of the path, which is not connected to the previous part of the path. Here: Move to (0,0) straight line to (2,0), move to (0,1) straight line to (2,1):
\draw (0,0) -- (2,0) (0,1) -- (2,1);
Connecting two points via straight lines that are only horizontal and vertical, use for first horizontal then vertial
\draw (0,0) -| (1,1);
or for first vertical then horizontal
\draw (0,0) |- (1,1);
Curved paths using a Bezier curve can be created using the "..controls() ..()" command, with one or two control points.
\draw (0,0) .. controls (1,1) .. (4,0)
(5,0) .. controls (6,0) and (6,1) .. (5,2);
A connected path can be closed using the "--cycle" operation:
\draw (1,0) -- (0,0) -- (0,1) -- cycle;
User-defined paths can be created using the "to" operation. Without an option it corresponds to a straight line, exactly like the double minus command. Using the "out" and "in" option a curved path can created. E.g. "[out=135,in=45]" causes the path to leave at an angle of 135 degree at the first coordinate and arrive at an angle of 45 degree at the second coordinate.
\draw (0,0) to (3,2); \draw (0,0) to[out=90,in=180] (3,2); \draw (0,0) to[bend right] (3,2);
For rectangles a special syntax exist. Use a move-to operation to one corner and after "rectangle" the coordinates of the diagonal corner. The last one becomes the new current point.
\draw (0,0) rectangle (1,1); \shade[top color=yellow, bottom color=black] (0,0) rectangle (2,-1);
Circles and ellipses paths are defined beginning with their center then using the "circle command" either with one length as radius of a circle or with two lengths as semi-axes of an ellipse.
\draw (0,0) circle [radius=1.5]; \draw (0,0) circle (2cm); % old syntax \draw (0,0) circle [x radius=1.5cm, y radius=10mm]; \draw (0,0) circle (1.2cm and 8mm); % old syntax \draw (0,0) circle [x radius=1cm, y radius=5mm, rotate=30]; \draw[rotate=30] (0,0) ellipse (20pt and 10pt); % old syntax
There are many more predefined commands for special paths, like "arc" for a part of an ellipse, "grid", "parabola", "sin", "cos" (sine or cosine curve in the interval [0,π/2]).
\draw (0,0) arc (0:270:8mm); \draw (0,0) arc (0:315:1.75cm and 1cm); \filldraw[fill=green!20!white, draw=green!40!black] (0,0) -- (12mm,0mm) arc (0:30:12mm) -- (0,0);
The fill color "green!20!white" means 20% green and 80% white mixed together.
\draw[step=0.5, gray, very thin] (-1.4,-1.4) grid (1.4,1.4); \draw (0,0) parabola (1,1.5) parabola[bend at end] (2,0); \draw (0,0) sin (1,1) cos (2,0) sin (3,-1) cos (4,0) sin (5,1);
To add arrow tips there are simple options for the drawing command:
\draw [->] (0,0) -- (30:20pt); \draw [<->] (1,0) arc (180:30:10pt); \draw [<<->] (2,0) -- ++(0.5,10pt) -- ++(0.5,-10pt) -- ++(0.5,10pt);
A loop can be realized by "\foreach ⟨variable⟩ in {⟨list of values⟩} ⟨commands⟩".
\foreach \x in {0,...,9} \draw (\x,0) circle (0.4);
[edit] Nodes
A node is typically a rectangle or circle or another simple shape with some text on it. In the simplest case, a node is just some text that is placed at some coordinate. Nodes are not part of the path itself, they are added to the picture after the path has been drawn.
Inside a path operation use the following syntax after a given coordinate:
node[<options>](<name>){<text>}
The "(<name>)" is a name for later reference and it is optional. If you only want to name a certain position without writing text there are two possibilities:
node[<options>](<name>){} coordinate[<options>](<name>)
Writing text along a given path using the note command is shown as simple example:
\draw[dotted] (0,0) node {1st node} -- (1,1) node {2nd node} -- (0,2) node {3rd node} -- cycle;
Possible options for the node command are e.g. "inner sep=<dimension>", "outer sep=<dimension>", "minimum size=<dimension>", "shape aspect=<aspect ratio>", "text=<color>", "font=", "align=<left_right_center>".
A node is centered at the current coordinate by default. Often it would be better to have the node to the besides the actual coordinate: Right ("right" or "anchor=west"), left ("left" or "anchor=east"), above ("above" or "anchor=south"), below ("below" or "anchor=north"). Combinations are also possible, like "anchor=north east" or "below left".
\fill[fill=yellow] (0,0) node {1st node} -- (1,1) node[circle,inner sep=0pt,draw] {2nd node} -- (0,2) node[fill=red!20,draw,double,rounded corners] {3rd node};
To place nodes on a line or a curve use the "pos=<fraction>" option, where fraction is a floating point number between 0 representing the previous coordinate and 1 representing the current coordinate.
\draw (0,0) -- (3,1) node[pos=0]{0} node[pos=0.5]{1/2} node[pos=0.9]{9/10};
There exist some abbreviations: "at start" for "pos=0", "very near start" for "pos=0.125", "near start" for "pos=0.25", "midway" for "pos=0.5", "near end" for "pos=0.75", "very near end" for "pos=0.875", "at end" for "pos=1".
The "sloped" option causes the node to be rotated to become a tangent to the curve.
Since nodes are often the only path operation on paths, there are special commands for creating paths containing only a node, the first with text ouput, the secound without:
\node[<options>](<name>) at (<coordinate>){<text>}; \coordinate[<options>](<name>) at (<coordinate>);
One can connect nodes using the nodes' labels as coordinates. Having "\path(0,0) node(x) {} (3,1) node(y) {};" defined, the node at (0,0) got the name "(x)" and the one at (3,1) got a label "(y)".
\path (0,0) node(x) {} (3,1) node(y) {}; \draw (x) -- (y);
Equivalent to
\coordinate (x) at (0,0); \coordinate (y) at (3,1); \draw (x) -- (y);
Path construction operations try to be clever, such that the path starts at the border of the node's shape and not from the node's center.
\path (0,0) node(x) {Hello World!} (3,1) node[circle,draw](y) {$\int_1^2 x \mathrm d x$}; \draw[->,blue] (x) -- (y); \draw[->,red] (x) -| node[near start,below] {label} (y); \draw[->,orange] (x) .. controls +(up:1cm) and +(left:1cm) .. node[above,sloped] {label} (y);
Once the node x has been defined, you can use anchors as defined above relative to (x) as "(x.<anchor>)", like "(x.north)".
[edit] Examples
Example 1
\documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture} \draw[thick,rounded corners=8pt] (0,0) -- (0,2) -- (1,3.25) -- (2,2) -- (2,0) -- (0,2) -- (2,2) -- (0,0) -- (2,0); \end{tikzpicture} \end{document}
Example 2
\documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture}[scale=3] \draw[step=.5cm, gray, very thin] (-1.2,-1.2) grid (1.2,1.2); \filldraw[fill=green!20,draw=green!50!black] (0,0) -- (3mm,0mm) arc (0:30:3mm) -- cycle; \draw[->] (-1.25,0) -- (1.25,0) coordinate (x axis); \draw[->] (0,-1.25) -- (0,1.25) coordinate (y axis); \draw (0,0) circle (1cm); \draw[very thick,red] (30:1cm) -- node[left,fill=white] {$\sin \alpha$} (30:1cm |- x axis); \draw[very thick,blue] (30:1cm |- x axis) -- node[below=2pt,fill=white] {$\cos \alpha$} (0,0); \draw (0,0) -- (30:1cm); \foreach \x/\xtext in {-1, -0.5/-\frac{1}{2}, 1} \draw (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north,fill=white] {$\xtext$}; \foreach \y/\ytext in {-1, -0.5/-\frac{1}{2}, 0.5/\frac{1}{2}, 1} \draw (1pt,\y cm) -- (-1pt,\y cm) node[anchor=east,fill=white] {$\ytext$}; \end{tikzpicture} \end{document}
[edit] Chemical Graphics
|
|
This book was last edited on 30 January 2012, and is still under heavy construction. Content that is added is likely to be moved/deleted/edited significantly in a short amount of time. All Wikibookians with knowledge in this subject are welcome to help out. You can remove this tag when the book has become more mature. |
chemfig is a package used to draw 2D chemical structures. It is an alternative to ochem. Whereas ochem requires Perl to draw chemical structures, chemfig uses the tikz package to produce its graphics. chemfig is used by adding the following to the preamble:
\usepackage{chemfig}
[edit] Basic Usage
The primary command used in this package is \chemfig{}:
\chemfig{<atom1><bond type>[<angle>,<coeff>,<tikz code>]<atom2>}
<angle> is the bond angle between two atoms (or nodes). There are three types of angles: absolute, relative, and predefined. Absolute angles give a precise angle (generally, 0 to 360, though they can also be negative), and are represented with the syntax [:<absolute angle>]. Relative angles require the syntax [::<relative angle>] and produce an angle relative to the angle of the preceding bond. Finally, predefined angles are whole numbers from 0 to 7 indicating intervals of 45 degrees. These are produced with the syntax [< predefined angle>]. The predefined angles and their corresponding absolute angles are represented in the diagram below.
<bond type> describes the bond attaching <atom1> and <atom2>. There are 9 different bond types:
\chemfig{A-B}\\ \chemfig{A=B}\\ \chemfig{A~B}\\ \chemfig{A>B}\\ \chemfig{A<B}\\ \chemfig{A>:B}\\ \chemfig{A<:B}\\ \chemfig{A>|B}\\ \chemfig{A<|B}\\ |
<coeff> represents the factor by which the bond's length will be multiplied.
<tikz code> includes additional options regarding the color or style of the bond.
A methane molecule, for instance, can be produced with the following code:
\chemfig{C(-[:0]H)(-[:90]H)(-[:180]H)(-[:270]H)} |
Linear molecules (such as methane) are a weak example of this, but molecules are formed in chemfig by nesting.
[edit] Skeletal Diagrams
Skeleton diagrams can be produced as follows:
\chemfig{-[:30]-[:-30]-[:30]} |
|
\chemfig{-[:30]=[:-30]-[:30]} |
[edit] Rings
Rings follow the syntax <atom>*<n>(code), where "n" indicates the number of sides in the ring and "code" represents the specific content of each ring (bonds and atoms).
\chemfig{A*6(-B-C-D-E-F-)} |
|
\chemfig{A*5(-B-C-D-E-)} |
|
\chemfig{*6(=-=-=-)} |
|
\chemfig{**5(------)} |
![]() |
[edit] Lewis Structures
Lewis structures can be created by using the command
\lewis{<electron angle><electron>,<atom>}
within \chemfig{}.
[edit] Ions
For example, consider an acetate ion:
\chemfig{-(-[1]O^{-})=[7]O} |
Because the chemfig commands enters the math mode, ion charges can be added as superscripts (one caveat: a negative ion requires that the minus sign be enclosed in brackets, as in the example).
The charge of an ion can be circled by using \oplus and \ominus:
\chemfig{-(-[1]O^{\ominus})=[7]O} |
Alternatively, charges can be placed above ions using \chemabove{}{}:
\chemfig{-\chemabove{N}{\scriptstyle\oplus}(=[1]O)-[7]O^{\ominus}} |
[edit] Resonance Structures and Formal Charges
Resonance structures require a few math commands:
% see "Advanced Mathematics" for use of \left and \right % add to preamble: % \usepackage{mathtools} % \Longleftrightarrow $\left\{\chemfig{O-N(=[:60]O)-[:300]O}\right\} \Longleftrightarrow \left\{\chemfig{O=N(-[:60]O)-[:300]O}\right\} \Longleftrightarrow \left\{\chemfig{O-N(-[:60]O)=[:300]O}\right\}$
[edit] Chemical Reactions
Chemical reactions can be created with the following commands:
\chemrel[<arg1>][<arg2>]{<arrow code>} |
\chemsign+ % produces a + |
In \chemrel{}, <arg1> and <arg2> represent text placed above and below the arrow, respectively.
There are four types of arrows that can be produced with tt>\chemrel{}:
A\chemrel{->}B\par A\chemrel{<-}B\par A\chemrel{<->}B\par A\chemrel{<>}B
[edit] Naming Chemical Graphics
Molecules can be named with the command
\chemname[<dim>]{\chemfig{<code of the molecule>}}{<name>}
<dim> is inserted between the bottom of the molecule and the top of the name defined by <name>. It is 1.5ex by default.
<name> will be centered relative to the molecule it describes.
\chemname{\chemfig{R-C(-[:-30]OH)=[:30]O}}{Carboxylic acid} \chemsign{+} \chemname{\chemfig{R’OH}}{Alcohol} \chemrel{->} \chemname{\chemfig{R-C(-[:-30]OR’)=[:30]O}}{Ester} \chemsign{+} \chemname{\chemfig{H_2O}}{Water}
In the reaction above, \chemname{} inserts 1.5ex plus the depth of the carboxylic acid molecule in between each molecule and their respective names. This is because the graphic for the first molecule in the reaction (carboxylic acid) extends deeper than the rest of the molecules. A different result is produced by putting the alcohol first:
\chemname{\chemfig{R’OH}}{Alcohol} \chemsign{+} \chemname{\chemfig{R-C(-[:-30]OH)=[:30]O}}{Carboxylic acid} \chemrel{->} \chemname{\chemfig{R-C(-[:-30]OR’)=[:30]O}}{Ester} \chemsign{+} \chemname{\chemfig{H_2O}}{Water}
This is fixed by adding \chemnameinit{<deepest molecule>} before the first instance of \chemname{} in a reaction and by adding \chemnameinit{} after the reaction:
\chemnameinit{\chemfig{R-C(-[:-30]OH)=[:30]O}} \chemname{\chemfig{R’OH}}{Alcohol} \chemsign{+} \chemname{\chemfig{R-C(-[:-30]OH)=[:30]O}}{Carboxylic acid} \chemrel{->} \chemname{\chemfig{R-C(-[:-30]OR’)=[:30]O}}{Ester} \chemsign{+} \chemname{\chemfig{H_2O}}{Water} \chemnameinit{}
Lastly, adding \\ in <name> will produce a line-break, allowing the name to span multiple lines.
[edit] Advanced Graphics
For advanced commands and examples, refer to the chemfig manual, where a more thorough and complete introduction to the package can be found.
[edit] Alternatives
In many cases, especially for more advanced diagrams, it may be easier to draw the graphics using external vector graphics software, and then import the file into the document (see LaTeX/Importing Graphics). However most software does not support LaTeX fonts or mathematical notation, which can result in ugly and inconsistent graphics. There are several solutions to this problem.
The easiest solution is to use the picture environment and then simply use the "put" command to put a graphics file inside the picture, along with any other desired LaTeX element. For example:
\setlength{\unitlength}{0.8cm} \begin{picture}(6,5) \put(3.5,0.4){$\displaystyle s:=\frac{a+b+c}{2}$} \put(1,1){\includegraphics[width=2cm,height=2cm]{picture.eps}} \end{picture} |
Another solution is to use textext, a plug-in for Inkscape which allows one to insert small LaTeX objects into .SVG images. These images can then be saved as .EPS (or .PDF) files which may then be imported into the LaTeX document proper.
Yet another solution is provided by lpic, which allows TeX annotations to imported graphics.
[edit] Using xfig to create pictures
An option that allows significantly more flexibility while creating graphics that are consistent with LaTeX is to use xfig. xfig is a drawing program, which allows exports into various formats from which it's possible to import into LaTeX. While the software is designed for Linux, it can be run using Macports for Macs and under any X-Window System for Windows.
There are many ways to use xfig to create graphics for LaTeX documents. One method is to export the drawing as a LaTeX document. This method, however, suffers from various drawbacks: lines can be drawn only at angles that are multiples of 30 and 45 degrees, lines with arrows can only be drawn at angles that are multiples of 45 degrees, several curves are not supported, etc.
Exporting a file as PDF/LaTeX or PS/LaTeX, on the other hand, offers a good deal more flexibility in drawing. Here's how it's done:
- Create the drawing in xfig. Wherever you need LaTeX text, such as a mathematical formula, enter a LaTeX string in a textbox.
- Use the Edit tool to open the properties of each of those textboxes, and change the option on the "Special Flag" field to Special. This tells LaTeX to interpret these textboxes when it opens the figure.
- Go to File -> Export and export the file as PDF/LaTeX (both parts) or PS/LaTeX (both parts), depending on whether you are using pdflatex or pslatex to compile your file.
- In your LaTeX document, where the picture should be, use the following, where "test" is replaced by the name of the image:
\begin{figure}[htbp] \centering \input{test.pdf_t} \caption{Your figure} \label{figure:example} \end{figure}
Observe that this is just like including a picture, except that rather than using \includegraphics, we use \input. If the export was into PS/LaTeX, the file extension to include would be .pstex_t instead of .pdf_t.
- Make sure to include packages graphicx and color in the file, with the usepackage command right below the documentclass command, like this:
\usepackage{graphicx} \usepackage{color}
And you're done!
For more details on using xfig with LaTeX, this chapter of the xfig User Manual may prove helpful.

