text:
LaTeX/Bibliography Management

For any academic/research writing, incorporating references into a document is an important task. Fortunately, LaTeX has a variety of features that make dealing with references much simpler, including built-in support for citing references. However, a much more powerful and flexible solution is achieved thanks to an auxiliary tool called BibTeX (which comes bundled as standard with LaTeX). Recently, BibTeX has been succeeded among many users by BibLaTeX, a tool configurable within LaTeX syntax.

BibTeX provides for the storage of all references in a bibliographic information file with the file extension, a kind of flat-file database. (BibLaTeX uses this same file format but with more and different bibliographic entry types and field types than BibTeX.) This database can be referenced in any LaTeX document, and citations made to any record that is contained within the file. This is often more convenient than embedding them at the end of every document written; a centralized bibliography source can be linked to as many documents as desired (write once, read many!). Of course, bibliographies can be split over as many files as one wishes, so there can be a file containing sources concerning topic A and another concerning topic B. When writing about topic AB, both of these files can be linked into the document (perhaps in addition to sources  specific to topic AB).

Embedded system
If you are writing only one or two documents and aren't planning on writing more on the same subject for a long time, you might not want to waste time creating a database of references you are never going to use. In this case you should consider using the basic and simple bibliography support that is embedded within LaTeX.

LaTeX provides an environment called  that you have to use where you want the bibliography; that usually means at the very end of your document, just before the   command. Here is a practical example:

OK, so what is going on here? The first thing to notice is the establishment of the environment. is a keyword that tells LaTeX to recognize everything between the begin and end tags as data for the bibliography. The mandatory argument, which I supplied after the begin statement, is telling LaTeX how wide the item label will be when printed. Note however, that the number itself is not the parameter, but the number of digits is. Therefore, I am effectively telling LaTeX that I will only need reference labels of one character in length, which ultimately means no more than nine references in total. If you want more than nine, then input any two-digit number, such as '56', which allows up to 99 references.

Next is the actual reference entry itself. This is prefixed with the  command. The cite_key should be a unique identifier for that particular reference, and is often some sort of mnemonic consisting of any sequence of letters, numbers and punctuation symbols (although not a comma). I often use the surname of the first author, followed by the last two digits of the year (hence lamport94). If that author has produced more than one reference for a given year, then I add letters after, 'a', 'b', etc. But, you should do whatever works for you. Everything after the key is the reference itself. You need to type it as you want it to be presented. I have put the different parts of the reference, such as author, title, etc., on different lines for readability. These linebreaks are ignored by LaTeX. The  command formats the title properly in italics.

Referring more specifically
If you want to refer to a certain page, figure or theorem in a text book, you can use the arguments to the  command:

The argument, "p. 215", will show up inside the same brackets. Note the tilde in, which replaces the end-of-sentence spacing with a non-breakable inter-word space. This non-breakable inter-word space is inserted because the end-of-sentence spacing would be too wide, and "p." should not be separated from the page number. The code  will produce the same result — in this case   in front of the page number will be added automatically; but it will not be added for.

Multiple citations
When a sequence of multiple citations is needed, you should use a single  command. The citations are then separated by commas. Here's an example:

The result will then be shown as citations inside the same brackets, depending on the citation style.

Bibliography styles
There are several different ways to format lists of bibliographic references and the citations to them in the text. These are called citation styles, and consist of two parts: the format of the abbreviated citation (i.e. the marker that is inserted into the text to identify the entry in the list of references) and the format of the corresponding entry in the list of references, which includes full bibliographic details.

Abbreviated citations can be of two main types: numbered or textual. Numbered citations (also known as the Vancouver referencing system) are numbered consecutively in order of appearance in the text, and consist in Arabic numerals in parentheses (1), square brackets [1], superscript1, or a combination thereof[1]. Textual citations (also known as the Harvard referencing system) use the author surname and (usually) the year as the abbreviated form of the citation, which is normally fully (Smith ) or partially enclosed in parenthesis, as in Smith . The latter form allows the citation to be integrated in the sentence it supports.

Below you can see three of the styles available with LaTeX:

Here are some more often used styles:

However, keep in mind that you will need to use the natbib package to use most of these.

No cite
If you only want a reference to appear in the bibliography, but not where it is referenced in the main text, then the  command can be used, for example:

A special version of the command,, includes all entries from the database, whether they are referenced in the document or not.

Natbib
Using the standard LaTeX bibliography support, you will see that each reference is numbered and each citation corresponds to the numbers. The numeric style of citation is quite common in scientific writing. In other disciplines, the author-year style, e.g., (Roberts, 2003), such as Harvard is preferred. The  package is one possible way to get such an output. In fact, it can supersede LaTeX's own citation commands, as Natbib allows the user to easily switch between Harvard or numeric.

The first job is to add the following to your preamble in order to get LaTeX to use the Natbib package:

An example of useful options is:

Also, you need to change the bibliography style file to be used, so edit the appropriate line at the bottom of the file so that it reads:. Once done, it is basically a matter of altering the existing  commands to display the type of citation you want.

Customization
The main commands simply add a t for 'textual' or p for 'parenthesized', to the basic  command. You will also notice how Natbib by default will compress references with three or more authors to the more concise 1st surname et al version. By adding an asterisk (*), you can override this default and list all authors associated with that citation. There are some other specialized commands that Natbib supports, listed in the table here. Keep in mind that for instance  does not support   and will automatically choose between all authors and et al..

The final area that I wish to cover about Natbib is customizing its citation style. There is a command called  that can be used to override the defaults and change certain settings. For example, I have put the following in the preamble:

The command requires six mandatory parameters.

 * 1) The symbol for the opening bracket.
 * 2) The symbol for the closing bracket.
 * 3) The symbol that appears between multiple citations.
 * 4) This argument takes a letter:
 * 5) * n - numerical style.
 * 6) * s - numerical superscript style.
 * 7) * any other letter - author-year style.
 * 8) The punctuation to appear between the author and the year (in parenthetical case only).
 * 9) The punctuation used between years, in multiple citations when there is a common author. e.g., (Chomsky 1956, 1957). If you want an extra space, then you need.

Some of the options controlled by  are also accessible by passing options to the natbib package when it is loaded. These options also allow some other aspect of the bibliography to be controlled, and can be seen in the table (right).

So as you can see, this package is quite flexible, especially as you can easily switch between different citation styles by changing a single parameter. Do have a look at the Natbib manual, it's a short document and you can learn even more about how to use it.

BibTeX
I have previously introduced the idea of embedding references at the end of the document, and then using the  command to cite them within the text. In this tutorial, I want to do a little better than this method, as it's not as flexible as it could be. I will concentrate on using BibTeX.

A BibTeX database is stored as a  file. It is a plain text file, and so can be viewed and edited easily. The structure of the file is also quite simple. An example of a BibTeX entry:

Each entry begins with the declaration of the reference type, in the form of. BibTeX knows of practically all types you can think of, common ones are: book, article, and for papers presented at conferences, there is inproceedings. In this example, I have referred to an article within a journal.

After the type, you must have a left curly brace ' ' to signify the beginning of the reference attributes. The first one follows immediately after the brace, which is the citation key, or the BibTeX key. This key must be unique for all entries in your bibliography. It is this identifier that you will use within your document to cross-reference it to this entry. It is up to you as to how you wish to label each reference, but there is a loose standard in which you use the author's surname, followed by the year of publication. This is the scheme that I use in this tutorial.

Next, it should be clear that what follows are the relevant fields and data for that particular reference. The field names on the left are BibTeX keywords. They are followed by an equals sign (=) where the value for that field is then placed. BibTeX expects you to explicitly label the beginning and end of each value. I personally use quotation marks ("), however, you also have the option of using curly braces ('{', '}'). But as you will soon see, curly braces have other roles, within attributes, so I prefer not to use them for this job as they can get more confusing. A notable exception is when you want to use characters with umlauts (ü, ö, etc), since their notation is in the format, and the quotation mark will close the one opening the field, causing an error in the parsing of the reference.  Using   in the preamble to the   source file can get round this, as the accented characters can just be stored in the   file without any need for special markup.  This allows a consistent format to be kept throughout the   file, avoiding the need to use braces when there are umlauts to consider.

Remember that each attribute must be followed by a comma to delimit one from another. You do not need to add a comma to the last attribute, since the closing brace will tell BibTeX that there are no more attributes for this entry, although you won't get an error if you do.

It can take a while to learn what the reference types are, and what fields each type has available (and which ones are required or optional, etc). So, look at this entry type reference and also this field reference for descriptions of all the fields. It may be worth bookmarking or printing these pages so that they are easily at hand when you need them. Much of the information contained therein is repeated in the following table for your convenience.

+ Required fields, o Optional fields *1 (Clarification needed) *2 (Clarification needed)

Authors
BibTeX can be quite clever with names of authors. It can accept names in forename surname or surname, forename. I personally use the former, but remember that the order you input them (or any data within an entry for that matter) is customizable and so you can get BibTeX to manipulate the input and then output it however you like. If you use the forename surname method, then you must be careful with a few special names, where there are compound surnames, for example "John von Neumann". In this form, BibTeX assumes that the last word is the surname, and everything before is the forename, plus any middle names. You must therefore manually tell BibTeX to keep the 'von' and 'Neumann' together. This is achieved easily using curly braces. So the final result would be "John {von Neumann}". This is easily avoided with the surname, forename, since you have a comma to separate the surname from the forename.

Secondly, there is the issue of how to tell BibTeX when a reference has more than one author. This is very simply done by putting the keyword and in between every author. As we can see from another example:

This book has three authors, and each is separated as described. Of course, when BibTeX processes and outputs this, there will only be an 'and' between the penultimate and last authors, but within the .bib file, it needs the ands so that it can keep track of the individual authors.

Standard templates
Standard templates that can be directly copied and filled in. Optional entries are marked in the core by a  prefix. Note that the  sign used in LaTeX for commenting lines does not work in BibTeX and creates invalid field name. In BibTeX, valid but unknown field names and names outside of an entry are ignored, leading to a popular commenting method. <--Be careful if you copy the following templates, the % sign is not valid to comment out lines in bibtex files. If you want to comment out a line, you have to put it outside the entry.-->

 * @article : An article from a magazine or a journal.
 * Required fields: author, title, journal, year.
 * Optional fields: volume, number, pages, month, note.

 * @book : A published book
 * Required fields: author/editor, title, publisher, year.
 * Optional fields: volume/number, series, address, edition, month, note.

 * @booklet : A bound work without a named publisher or sponsor.
 * Required fields: title.
 * Optional fields: author, howpublished, address, month, year, note.

 * @conference : Equal to inproceedings
 * Required fields: author, title, booktitle, year.
 * Optional fields: editor, volume/number, series, pages, address, month, organization, publisher, note.

 * @inbook : A section of a book without its own title.
 * Required fields: author/editor, title, chapter and/or pages, publisher, year.
 * Optional fields: volume/number, series, type, address, edition, month, note.

 * @incollection : A section of a book having its own title.
 * Required fields: author, title, booktitle, publisher, year.
 * Optional fields: editor, volume/number, series, type, chapter, pages, address, edition, month, note.

 * @inproceedings : An article in a conference proceedings.
 * Required fields: author, title, booktitle, year.
 * Optional fields: editor, volume/number, series, pages, address, month, organization, publisher, note.

 * @manual : Technical manual
 * Required fields: title.
 * Optional fields: author, organization, address, edition, month, year, note.

 * @mastersthesis : Master's thesis
 * Required fields: author, title, school, year.
 * Optional fields: type (eg. "diploma thesis"), address, month, note.

 * @misc : Template useful for other kinds of publication
 * Required fields: none
 * Optional fields: author, title, howpublished, month, year, note.

 * @phdthesis : Ph.D. thesis
 * Required fields: author, title, year, school.
 * Optional fields: address, month, keywords, note.

 * @proceedings : The proceedings of a conference.
 * Required fields: title, year.
 * Optional fields: editor, volume/number, series, address, month, organization, publisher, note.

 * @techreport : Technical report from educational, commercial or standardization institution.
 * Required fields: author, title, institution, year.
 * Optional fields: type, number, address, month, note.

 * @unpublished : An unpublished article, book, thesis, etc.
 * Required fields: author, title, note.
 * Optional fields: month, year.

Non-standard templates

 * @patent
 * BibTeX entries can be exported from Google Patents.
 * (see Cite Patents with Bibtex for an alternative)

 * @collection

 * @electronic

 * @Unpublished
 * For citing arXiv.org papers in a REVTEX-style article
 * (see REVTEX Author's guide)

Preserving case of letters
In the event that BibTeX has been set by the chosen style not to preserve all capitalization within titles, problems can occur, especially if you are referring to proper nouns, or acronyms. To tell BibTeX to keep them, use the good old curly braces around the letter in question, (or letters, if it's an acronym) and all will be well! It is even possible that lower-case letters may need to be preserved - for example if a chemical formula is used in a style that sets a title in all caps or small caps, or if "pH" is to be used in a style that capitalises all first letters.

However, avoid putting the whole title in curly braces, as it will look odd if a different capitalization format is used:

For convenience though, many people simply put double curly braces, which may help when writing scientific articles for different magazines, conferences with different BibTex styles that do sometimes keep and sometimes not keep the capital letters:

As an alternative, try other BibTex styles or modify the existing. The approach of putting only relevant text in curly brackets is the most feasible if using a template under the control of a publisher, such as for journal submissions. Using curly braces around single letters is also to be avoided if possible, as it may mess up the kerning, especially with biblatex, so the first step should generally be to enclose single words in braces.

A few additional examples
Below you will find a few additional examples of bibliography entries. The first one covers the case of multiple authors in the Surname, Firstname format, and the second one deals with the incollection case.

If you have to cite a website you can use @misc, for example:

The note field comes in handy if you need to add unstructured information, for example that the corresponding issue of the journal has yet to appear:

Getting current LaTeX document to use your .bib file
At the end of your LaTeX file (that is, after the content, but before ), you need to place the following commands:

Bibliography styles are files recognized by BibTeX that tell it how to format the information stored in the .bib file when processed for output. And so the first command listed above is declaring which style file to use. The style file in this instance is plain.bst (which comes as standard with BibTeX). You do not need to add the .bst extension when using this command, as it is assumed. Despite its name, the plain style does a pretty good job (look at the output of this tutorial to see what I mean).

The second command is the one that actually specifies the .bib file you wish to use. The ones I created for this tutorial were called sample1.bib, sample2.bib,. . ., samplen.bib, but once again, you don't include the file extension. At the moment, the .bib file is in the same directory as the LaTeX document too. However, if your .bib file was elsewhere (which makes sense if you intend to maintain a centralized database of references for all your research), you need to specify the path as well, e.g  or   (if the   file is in the parent directory of the   document that calls it).

Now that LaTeX and BibTeX know where to look for the appropriate files, actually citing the references is fairly trivial. The  is the command you need, making sure that the ref_key corresponds exactly to one of the entries in the .bib file. If you wish to cite more than one reference at the same time, do the following:.

Why won't LaTeX generate any output?
The addition of BibTeX adds extra complexity for the processing of the source to the desired output. This is largely hidden from the user, but because of all the complexity of the referencing of citations from your source LaTeX file to the database entries in another file, you actually need multiple passes to accomplish the task. This means you have to run LaTeX a number of times. Each pass will perform a particular task until it has managed to resolve all the citation references. Here's what you need to type (into command line): (Extensions are optional, if you put them note that the bibtex command takes the AUX file as input.)

After the first LaTeX run, you will see errors such as:

LaTeX Warning: Citation `lamport94' on page 1 undefined on input line 21. ... LaTeX Warning: There were undefined references.

The next step is to run bibtex on that same LaTeX source (or more precisely the corresponding AUX file, however not on the actual .bib file) to then define all the references within that document. You should see output like the following:

This is BibTeX, Version 0.99c (Web2C 7.3.1) The top-level auxiliary file: latex_source_code.aux The style file: plain.bst Database file #1: sample.bib

The third step, which is invoking LaTeX for the second time will see more errors like "LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.". Don't be alarmed, it's almost complete. As you can guess, all you have to do is follow its instructions, and run LaTeX for the third time, and the document will be output as expected, without further problems.

If you want a pdf output instead of a dvi output you can use <tt>pdflatex</tt> instead of <tt>latex</tt> as follows:

(Extensions are optional, if you put them note that the bibtex command takes the AUX file as input.)

Note that if you are editing your source in vim and attempt to use command mode and the current file shortcut (%) to process the document like this:

You will get an error similar to this:

It appears that the file extension is included by default when the current file command (%) is executed. To process your document from within vim, you must explicitly name the file without the file extension for bibtex to work, as is shown below:

 * 1)   (without file extension, it looks for the AUX file as mentioned above)
 * 1)   (without file extension, it looks for the AUX file as mentioned above)

Another option exists if you are running Unix/Linux or any other platform where you have make. Then you can simply create a Makefile and use vim's make command or use make in shell. The Makefile would then look like this:

latex_source_code.pdf: latex_source_code.tex latex_source_code.bib pdflatex latex_source_code.tex bibtex latex_source_code.aux pdflatex latex_source_code.tex pdflatex latex_source_code.tex Frequently occuring errors are:

 * Bibtex is irritated by spaces in the bibliography file's name. Spaces in file names are not allowed with BibTeX, other limitations such as a maximal path length of 40 characters are valid too. Solution: Copy the bib file into your folder or rename folders to names without spaces.
 * Empty bibliography: Did you cite something in the document (search for \cite or similar words)? Otherwise, LaTeX will not generate a bibliography in the PDF. Solutions: Use \nocite{*} to list all entries in the bibliography, without regard to whether they are cited or not. Or simply: Cite something.
 * BibTeX keeps complaining over an entry with quotation marks despite the syntax looks correct? It may be that the quotation marks are similar looking, but wrong characters. (" vs. '' ). Solution: Try to exchange the quotation marks with their correct counterparts.

Including URLs in bibliography
As you can see, there is no field for URLs. One possibility is to include Internet addresses in  field of   or   field of ,  ,  :

Note the usage of  command to ensure proper appearance of URLs.

Another way is to use special field <tt>url</tt> and make bibliography style recognise it.

You need to use  in the first case or   in the second case.

Styles provided by Natbib (see below) handle this field, other styles can be modified using urlbst program. Modifications of three standard styles (plain, abbrv and alpha) are provided with urlbst.

If you need more help about URLs in bibliography, visit FAQ of UK List of TeX.

Customizing bibliography appearance
One of the main advantages of BibTeX, especially for people who write many research papers, is the ability to customize your bibliography to suit the requirements of a given publication. You will notice how different publications tend to have their own style of formatting references, to which authors must adhere if they want their manuscripts published. In fact, established journals and conference organizers often will have created their own bibliography style (.bst file) for those users of BibTeX, to do all the hard work for you.

It can achieve this because of the nature of the .bib database, where all the information about your references is stored in a structured format, but nothing about style. This is a common theme in LaTeX in general, where it tries as much as possible to keep content and presentation separate.

A bibliography style file (<tt>.bst</tt>) will tell LaTeX how to format each attribute, what order to put them in, what punctuation to use in between particular attributes etc. Unfortunately, creating such a style by hand is not a trivial task. Which is why <tt>Makebst</tt> (also known as custom-bib) is the tool we need.

<tt>Makebst</tt> can be used to automatically generate a .bst file based on your needs. It is very simple, and actually asks you a series of questions about your preferences. Once complete, it will then output the appropriate style file for you to use.

It should be installed with the LaTeX distribution (otherwise, you can download it) and it's very simple to initiate. At the command line, type:

latex makebst

LaTeX will find the relevant file and the questioning process will begin. You will have to answer quite a few (although, note that the default answers are pretty sensible), which means it would be impractical to go through an example in this tutorial. However, it is fairly straight-forward. And if you require further guidance, then there is a comprehensive manual available. I'd recommend experimenting with it and seeing what the results are when applied to a LaTeX document.

If you are using a custom built .bst file, it is important that LaTeX can find it! So, make sure it's in the same directory as the LaTeX source file, unless you are using one of the standard style files (such as plain or plainnat, that come bundled with LaTeX - these will be automatically found in the directories that they are installed. Also, make sure the name of the <tt>.bst</tt> file you want to use is reflected in the  command (but don't include the <tt>.bst</tt> extension!).

Localizing bibliography appearance
When writing documents in languages other than English, you may find it desirable to adapt the appearance of your bibliography to the document language. This concerns words such as editors, and, or in as well as a proper typographic layout. The <tt>babelbib</tt> package can be used here. For example, to layout the bibliography in German, add the following to the header:

Alternatively, you can layout each bibliography entry according to the language of the cited document:

The language of an entry is specified as an additional field in the BibTeX entry:

For <tt>babelbib</tt> to take effect, a bibliography style supported by it - one of <tt>babplain</tt>, <tt>babplai3</tt>, <tt>babalpha</tt>, <tt>babunsrt</tt>, <tt>bababbrv</tt>, and <tt>bababbr3</tt> - must be used:

Showing unused items
Usually LaTeX only displays the entries which are referred to with. It's possible to make uncited entries visible:

Getting bibliographic data
Many online databases provide bibliographic data in BibTeX-Format, making it easy to build your own database. For example, Google Scholar offers the option to return properly formatted output, which can also be turned on in the settings page.

One should be alert to the fact that bibliographic databases are frequently the product of several generations of automatic processing, and so the resulting BibTex code is prone to a variety of minor errors, especially in older entries.

Helpful tools

 * BibDesk BibDesk is a bibliographic reference manager for Mac OS X. It features a very usable user interface and provides a number of features like smart folders based on keywords and live tex display.
 * BibSonomy — A free social bookmark and publication management system based on BibTeX.
 * BibTeXSearch BibTeXSearch is a free searchable BibTeX database spanning millions of academic records.
 * Bibtex Editor - An online BibTeX entry generator and bibliography management system. Possible to import and export Bibtex files.
 * Bibwiki Bibwiki is a Specialpage for MediaWiki to manage BibTeX bibliographies. It offers a straightforward way to import and export bibliographic records.
 * cb2Bib The cb2Bib is a tool for rapidly extracting unformatted, or unstandardized bibliographic references from email alerts, journal Web pages, and PDF files.
 * Citavi Commercial software (with size-limited free demo version) which even searches libraries for citations and keeps all your knowledge in a database. Export of the database to all kinds of formats is possible. Works together with MS Word and Open Office Writer. Moreover plug ins for browsers and Acrobat Reader exist to automatically include references to your project.
 * DokuWiki DokuWiki is a Bibtext plugin that allows for the inclusion of bibtex formatted citations in DokuWiki pages and displays them in APA format. Note: This Plugins is vulnerable to an XSS attack -> http://www.dokuwiki.org/plugin:bibtex
 * Ebib — a BibTeX database manager for Emacs, well resolved and never more than a few keystrokes away.
 * JabRef is a Java program (under the GPL license) which lets you search many bibliographic databases such as Medline, Citeseer, IEEEXplore and arXiv and feed and manage your BibTeX local databases with your selected articles. Based on BiBTeX, JabRef can export in many other output formats such as html, MS Word or EndNote.
 * KBib Another BibTeX editor for KDE. It has similar capabilities, and slightly different UI. Features include BibTeX reference generation from PDF files, plain text, DOI, arXiv & PubMed IDs. Web queries to Google Scholar, PubMer, arXiv and a number of other services are also supported.
 * KBibTeX KBibTeX is a BibTeX editor for KDE to edit bibliographies used with LaTeX. Features include comfortable input masks, starting web queries (e. g. Google or PubMed) and exporting to PDF, PostScript, RTF and XML/HTML. As KBibTeX is using KDE's KParts technology, KBibTeX can be embedded into Kile or Konqueror.
 * Literatur-Generator is a German-language online tool for creating a bibliography (Bibtex, Endnote, Din 1505, ...).
 * Mendeley Mendeley is cost-free academic software for managing PDFs which can manage a bibliography in Open Office and read BibTeX.
 * Qiqqa Qiqqa is a free research manager that has built-in support for automatically associating BibTeX records with your PDFs and a 'BibTeX Sniffer' for helping you semi-automatically find BibTeX records.
 * Referencer Referencer is a Gnome application to organise documents or references, and ultimately generate a BibTeX bibliography file.
 * Synapsen — Hypertextual Card Index / Reference Manager with special support for BiBTeX / biblatex, written in Java.
 * Zotero Zotero is a free and open reference manager working as a standalone application, capable of importing and exporting bib files. Zotero has browser plugins for Chrome and Firefox.

Summary
Although it can take a little time to get to grips with BibTeX, in the long term, it's an efficient way to handle your references. It's not uncommon to find .bib files on websites that people compile as a list of their own publications, or a survey of relevant works within a given topic, etc. Or in those huge, online bibliography databases, you often find BibTeX versions of publications, so it's a quick cut-and-paste into your own .bib file, and then no more hassle!

Having all your references in one place can be a big advantage. And having them in a structured form, that allows customizable output is another one. There are a variety of free utilities that can load your .bib files, and allow you to view them in a more efficient manner, as well as sort them and check for errors.

Bibliography in the table of contents
If you are writing a book or report, you'll likely insert your bibliography using something like:

Or, if you are using BibTeX, your references will be saved in a .bib file, and your TeX document will include the bibliography by these commands:

Both of these examples will create a chapter-like (or section-like) output showing all your references. But even though the resulting “References” looks like a chapter or section, it will not be handled quite the same: it will not appear in the Table of Contents.

Using tocbibind
The most comfortable way of adding your bibliography to the table of contents is to use the dedicated package tocbibind that works with many standard document classes. Simply include this code in the preamble of your document:

This will include the Bibliography in the Table of Contents without numbering. If you want to have proper numbering, include the following code in the preamble:

The tocbibind package can also handle including the List of Figures, List of Tables and the Table of Contents itself in the Table of Contents. It has many options for numbering, document structure etc. to fit almost any scenario. See the tocbibind CTAN page for detailed documentation.

As unnumbered item
If you want your bibliography to be in the table of contents, just add the following two lines just before the thebibliography environment:

(OR  if you're writing an article)

The first line just terminates the current paragraph and page. If you are writing a book, use <tt>\cleardoublepage</tt> to match the style used. The second line will add a line in the Table of Contents (first option, toc), it will be like the ones created by chapters (second option, chapter), and the third argument will be printed on the corresponding line in the Table of Contents; here Bibliography was chosen because it's the same text the thebibliography environment will automatically write when you use it, but you are free to write whatever you like. If you are using a separate bib file, add these lines between <tt>\bibliographystyle</tt> and <tt>\bibliography</tt>.

If you use hyperref package, you should also use the  command to enable hyperlinking from the table of contents to bibliography.

This trick is particularly useful when you have to insert the bibliography in the Table of Contents, but it can work for anything. When LaTeX finds the code above, it will record the info as described and the current page number, inserting a new line in the Contents page.

As numbered item
If you instead want bibliography to be numbered section or chapter, you'll likely use this way:

Another even easier solution is to use  inside of the   block:

You may wish to use  followed by   to counteract the extra space the blank   inserts.

If you are using BibTeX, the  command, and the book or report class, you will need to redefine   instead of   like so.

biblatex
As we said before, biblatex is widely considered the successor of BibTeX. Intended as a full replacement for BibTeX, it is more configurable in its output and provides a multitude of new styles (for output) and fields (for the database) that can be used in a document. For now, refer to its comprehensive documentation on CTAN.

Entry and field types in .bib files
The following table shows most field types. Some field types are lists, either, others are. A  can either be given in parts or full, some   are necessary, page references are provided as   and certain special fields contain   code. There are many kinds of.

Some entry types are hard to distinguish and are treated the same by standard styles:
 * is the same as hypothetic * and therefore encompasses existing

Some field types are defined, but the documentation does not say which entry types they can be used with. This is either because they depend on another field being set to be useful or they can always be used in a user-defined manner, but will never be used in standard styles:

The only field that is always mandatory, is. All entry types also require either  or   and they specify which of   and   they expect or whether they can use both. Some field types can optionally be used with any entry type: All physical (print) entry types share further optional field types:

Multimedia entry types and legal entry types are defined, but not yet supported (well).

The entry types,   and   are special.

Printing bibliography
Presuming we have defined our references in a file called references.bib, we add this to biblatex by adding the following to the preamble:

Print the bibliography with this macro (usually at the end of the document body):

Printing separate bibliographies
We want to separate the bibliography into papers, books and others

If the bib entries are located in multiple files we can add them like this:

We can also filter on other fields, such as entrysubtype. If we define our online resources like this:

we filter with

Example with prefix keys, subheadings and table of contents
As the numbering of the bibliographies are independent, it can be useful to also separate the bibliographies using prefixnumbers such as a, b and c. In addition we add a main heading for the bibliographies and add that to the table of contents.

To make Hyperref links point to the correct bibliography section, we also add  before printing each bibliography

To add each of the bibliographies to the table of contents as sub-sections to the main Bibliography, replace  with.

Using
This package is for multiple Bibliographies for different sections in your work. For example, you can generate a bibliography for each chapter. You can find information about the package on CTAN

Using
The bibtopic-Package is created to split the citations among more files, so that you can divide the bibliography into more parts. It generates a separate aux file for each bibliography section, so you will have to run bibtex on each of those (see the package documentation for more details).

Notes and references
LaTeX/Gestion de la bibliographie LaTeX/Управление библиографией

title: LaTeX/Bibliography Management


text:
LaTeX/Tables

Tables are a common feature in academic writing, often used to summarize research results. Mastering the art of table construction in LaTeX is therefore necessary to produce quality papers and with sufficient practice one can print beautiful tables of any kind.

Keeping in mind that LaTeX is not a spreadsheet, it makes sense to use a dedicated tool to build tables and then to export these tables into the document. Basic tables are not too taxing, but anything more advanced can take a fair bit of construction; in these cases, more advanced packages can be very useful. However, first it is important to know the basics. Once you are comfortable with basic LaTeX tables, you might have a look at more advanced packages or the export options of your favorite spreadsheet. Thanks to the modular nature of LaTeX, the whole process can be automated in a fairly comfortable way.

Introduction
LaTeX has built-in support to typeset tables and provides two environments: and. To typeset material in rows and columns, the environment is needed; the optional  environment is a container for floating material similar to, into which a  environment may be included.

The environment contains the caption and defines the float for the table, i.e., where in the document the table should be positioned and whether we want it to be displayed centered. The and  commands can be used in the same way as for pictures. For more information about the environment, see the Floating with table section.

In any case, the actual content of the table is contained within the environment.

The tabular environment
The environment can be used to typeset tables with optional horizontal and vertical lines. LaTeX determines the width of the columns automatically.

The first line of the environment has the form:

The argument tells LaTeX the alignment to be used in each column and the vertical lines to insert.

The number of columns does not need to be specified as it is inferred by looking at the number of arguments provided. It is also possible to add vertical lines between the columns here. The following symbols are available to describe the table columns (some of them require that the package has been loaded):

By default, if the text in a column is too wide for the page, LaTeX won’t automatically wrap it. Using you can define a special type of column which will wrap-around the text as in a normal paragraph. You can pass the width using any unit supported by LaTeX, such as 'pt' and 'cm', or command lengths, such as. You can find a list in chapter Lengths.

The optional parameter can be used to specify the vertical position of the table relative to the baseline of the surrounding text. In most cases, you will not need this option. It becomes relevant only if your table is not in a paragraph of its own. You can use the following letters:

To specify a font format (such as bold, italic, etc.) for an entire column, you can add before you declare the alignment. For example will indicate a three column table with the first one aligned to the left and in bold font, the second one aligned in the center and with normal font, and the third aligned to the right and in italic. The "array" package needs to be activated in the preamble for this to work.

In the first line you have pointed out how many columns you want, their alignment and the vertical lines to separate them. Once in the environment, you have to introduce the text you want, separating between cells and introducing new lines. The commands you have to use are the following:

Note, any white space inserted between these commands is purely down to one's preferences. I personally add spaces between to make it easier to read.

Basic examples
This example shows how to create a simple table in LaTeX. It is a three-by-three table, but without any lines.

Expanding upon that by including some vertical lines:

To add horizontal lines to the very top and bottom edges of the table:

And finally, to add lines between all rows, as well as centering (notice the use of the center environment - of course, the result of this is not obvious from the preview on this web page):

Text wrapping in tables
LaTeX's algorithms for formatting tables have a few shortcomings. One is that it will not automatically wrap text in cells, even if it overruns the width of the page. For columns that will contain text whose length exceeds the column's desired width, it is recommended that you use the attribute and specify the desired width of the column (although it may take some trial-and-error to get the result you want). For a more convenient method, have a look at The tabularx package, or The tabulary package.

Instead of, use the attribute to have the lines aligned toward the middle of the box or the  attribute to align along the bottom of the box.

Here is a simple example. The following code creates two tables with the same code; the only difference is that the last column of the second one has a defined width of 5 centimeters, while in the first one we didn't specify any width. Compiling this code:

You get the following output:

Note that the first table has been cropped, since the output is wider than the page width.

Manually broken paragraphs in table cells
Sometimes it is necessary to not rely on the breaking algorithm when using the specifier, but rather specify the line breaks by hand. In this case it is easiest to use a :

Here the argument controls the placement of the text inside the box. Other allowed values are for center and  for bottom.

Space between columns
To tweak the space between columns (LaTeX will by default choose very tight columns), one can alter the column separation:. The default value is 6pt.

One can also introduce a horizontal space with hspace like this: There are different options for the hspace length.

Space between rows
Re-define the command to set the space between rows:

Default value is 1.0.

An alternative way to adjust the rule spacing is to add before or after the  and  commands:

You may also specify the skip after a line explicitly using glue after the line terminator

Other environments inside tables
If you use some LaTeX environments inside table cells, like or :

you might encounter errors similar to ! LaTeX Error: Something's wrong--perhaps a missing \item.

To solve this problem, change column specifier to "paragraph" (, or ).

Defining multiple columns
It is possible to define many identically aligned columns at once using the syntax. This is particularly useful when your table has many columns.

Here is a table with six centered columns flanked by a single column on each side:

Column specification using >{\cmd} and <{\cmd}
The column specification can be altered using the package. This is done in the argument of the tabular environment using for commands executed right before each column element and for commands to be executed right after each column element. As an example: to get a column in math mode enter:. Another example is changing the font: to print the column in a small font.

The argument of the and  specifications must be correctly balanced when it comes to {{LaTeX/LaTeX|code={}} and } characters. This means that is valid, while  will not work and {{LaTeX/LaTeX|code=>{\textbf{}}} is not valid. If there is the need to use the text of the table as an argument (for instance, using the to produce bold text), one should use the  and  commands:  produces the intended effect. This works only for some basic LaTeX commands. For other commands, such as to underline text, it is necessary to temporarily store the column text in a box using. First, you must define such a box with and then you can define:

{{LaTeX/Usage|code= >{\begin{lrbox}{\boxname} }% l% <{\end{lrbox}% \underline{\unhbox\boxname} }% } }}

This stores the text in a box and afterwards, takes the text out of the box with (this destroys the box, if the box is needed again one should use  instead) and passing it to. (For LaTeX2e, you may want to use instead of .)

This same trick done with instead of  can force all lines in a table to have equal height, instead of the natural varying height that can occur when e.g. math terms or superscripts occur in the text.

Here is an example showing the use of both and  :

Note the use of instead of  to avoid a  error.

@ and ! expressions
The column separator can be specified with the or  constructs.

It typically takes some text as its argument, and when appended to a column, it will automatically insert that text into each cell in that column before the actual data for that cell. The command kills the inter-column space and replaces it with whatever is between the curly braces. To keep the initial space, use. To add space, use.

Admittedly, this is not that clear, and so will require a few examples to clarify. Sometimes, it is desirable in scientific tables to have the numbers aligned on the decimal point. This can be achieved by doing the following:

The space-suppressing qualities of the @-expression actually make it quite useful for manipulating the horizontal spacing between columns. Given a basic table, and varying the column descriptions:

Aligning columns at decimal points using dcolumn
Instead of using @-expressions to build columns of decimals aligned to the decimal point (or equivalent symbol), it is possible to center a column on the decimal separator using the package, which provides a new column specifier for floating point data. See the dcolumn package documentation for more information, but a simple way to use is as follows.

A negative argument provided for the number of decimal places in the new column type allows unlimited decimal places, but may result in rather wide columns. Rounding is not applied, so the data to be tabulated should be adjusted to the number of decimal places specified. Note that a decimal aligned column is typeset in math mode, hence the use of \mathrm for the column heading in the example above. Also, text in a decimal aligned column (for example the header) will be right-aligned before the decimal separator (assuming there's no decimal separator in the text). While this may be fine for very short text, or numeric column headings, it looks cumbersome in the example above. A solution to this is to use the command described below, specifying a single column and its alignment. For example to center the header Decimal over its column in the above example, the first line of the table itself would be

Bold text and dcolumn
To draw attention to particular entries in a table, it may be nice to use bold text. Ordinarily this is easy, but as dcolumn needs to see the decimal point it is rather harder to do. In addition, the usual bold characters are wider than their normal counterparts, meaning that although the decimals may align nicely, the figures (for more than 2--3 digits on one side of the decimal point) will be visibly misaligned. It is however possible to use normal width bold characters and define a new bold column type, as shown below.

Row specification
It might be convenient to apply the same command over every cell of a row, just as for column. Unfortunately the environment cannot do that by default. We will need instead, which provides the  option.

Spanning
To complete this tutorial, we take a quick look at how to generate slightly more complex tables. Unsurprisingly, the commands necessary have to be embedded within the table data itself.

Rows spanning multiple columns
The command for this looks like this:. is the number of subsequent columns to merge; is either, , , or to have text wrapping specify a width. And is simply the actual data you want to be contained within that cell. A simple example:

Columns spanning multiple rows
The first thing you need to do is add to the preamble. This then provides the command needed for spanning rows:. The arguments are pretty simple to deduce ( for the width means the content's natural width).

The main thing to note when using is that a blank entry must be inserted for each appropriate cell in each subsequent row to be spanned.

If there is no data for a cell, just don't type anything, but you still need the "&" separating it from the next column's data. The astute reader will already have deduced that for a table of $$n$$ columns, there must always be $$n-1$$ ampersands in each row (unless is also used).

Spanning in both directions simultaneously
Here is a nontrivial example of how to use spanning in both directions simultaneously and have the borders of the cells drawn correctly:

The command is just used to draw vertical borders both on the left and on the right of the cell. Even when combined with, it still draws vertical borders that only span the first row. To compensate for that, we add in the following rows spanned by the multirow. Note that we cannot just use to draw horizontal lines, since we do not want the line to be drawn over the text that spans several rows. Instead we use the command and opt out the first column that contains the text "Powers".

Here is another example exploiting the same ideas to make the familiar and popular "2x2" or double dichotomy:

Resize tables
The packages features the command  which can be used with  to specify the height and width of a table. The following example shows how to resize a table to 8cm width while maintaining the original width/height ratio.

Resizing table including the caption

Alternatively you can use in the same way but with ratios rather than fixed sizes:

Changing font size
A table can be globally switched to a different font size by simply adding the desired size command (here: ) in the table scope, which may be after the statement if you use floats, otherwise you need to add a group delimiter.

Alternatively, you can change the default font for all the tables in your document by placing the following code in the preamble:

See Fonts for named font sizes. The table caption font size is not affected. To control the caption font size, see Caption Styles.

It is also possible to change the vertical space between rows using before.

Alternate row colors in tables
The package provides the necessary commands to produce tables with alternate row colors, when loaded with the  option. The command has to be specified right before the  environment starts.

The command is available to deactivate highlighting from a specified row until the end of the table. Highlighting can be reactivated within the table via the command. If while using these commands you experience "misplaced \noalign errors" then use the commands at the very beginning or end of a row in your tabular.

or

Colors of individual cells
As above this uses the package.

Width and stretching
We keep providing documentation for and.

The tabular* environment
This is basically a slight extension on the original tabular version, although it requires an extra argument (before the column descriptions) to specify the preferred width of the table.

However, that may not look quite as intended. The columns are still at their natural width (just wide enough to fit their contents) while the rows are as wide as the table width specified. If you do not like this default, you must also explicitly insert extra column space. LaTeX has rubber lengths, which, unlike others, are not fixed. LaTeX can dynamically decide how long the lengths should be. So, an example of this is the following.

You will notice the construct added at the beginning of the column description. Within it is the command, which requires a width. A fixed width could have been used. However, by using a rubber length, such as, the columns are automatically spaced evenly.

The tabularx package
This package provides a table environment called, which is similar to the environment except that it has a new column specifier  (in uppercase). The column(s) specified with this specifier will be stretched to make the table as wide as specified, greatly simplifying the creation of tables.

The content provided for the boxes is treated as for a column, except that the width is calculated automatically. If you use the package, you may also apply any or  command to achieve specific behavior (like , or ) as described previously.

Another option is to use to format selected columns in a different way. It defines a new column specifier, e.g. (in uppercase). In this example, the second and fourth column is adjusted in a different way :

Tabularx with rows spanning multiple columns using. The two central columns are posing as one by using the option. Note that the width (which in this example is 2) should equal the (in this example 1+1) width of the spanned columns:

In a way analogous to how new commands with arguments can be created with \newcommand, new column types with arguments can be created with \newcolumntype as follows:

where since there are 4 columns, the sum of the \hsize's (1 + 0.5 + 0.5 + 2) must be equal to 4. The default value used by tabularx for \hsize is 1.

The tabulary package
tabulary is a modified allowing width of columns set for equal heights. allows easy and convenient writing of well balanced tables.

The problem with is that it leaves much blank if your cells are almost empty. Besides, it is not easy to have different column sizes.

tries to balance the column widths so that each column has at least its natural width, without exceeding the maximum length.

The first parameter is the maximum width. will try not to exceed it, but it will not stretch to it if there is not enough content, contrary to.

The second parameter is the column disposition. Possible values are those from the environment, plus

These are all capitals.

The tabu environment
It works pretty much like.

Note: tabu is currently broken and unmaintained

specifies the target width. The parameter can have an optional span factor.

Table across several pages
Long tables are natively supported by LaTeX thanks to the environment, which replaces both the  and  environments or rather combines them into a single environment. Unfortunately, this environment does not support stretching (X columns).

The package (which is no longer maintained) provides the  environment. It has most of the features of, with the additional capability to span multiple pages.

LaTeX can do well with long tables: you can specify a header that will repeat on every page, a header for the first page only, and the same for the footer.

It uses syntax similar to, so you should have a look at its documentation if you want to know more.

Alternatively you can try one of the following packages supertabular or xtab, an extended and somewhat improved version of.

Partial vertical lines
Adding a partial vertical line to an individual cell:

Removing part of a vertical line in a particular cell:

Vertically centered images
Inserting images into a table row will align it at the top of the cell. By using the package this problem can be solved. Defining a new columntype will keep the image vertically centered.

Or use a parbox to center the image.

A raisebox works as well, also allowing to manually fine-tune the alignment with its first parameter.

Footnotes in tables
The environment does not handle footnotes properly. The fixes that.

Professional tables
Many professionally typeset books and journals feature simple tables, which have appropriate spacing above and below lines, and almost never use vertical rules. Many examples of LaTeX tables (including this Wikibook) showcase the use of vertical rules (using "|"), and double-rules (using or "||"), which are regarded as unnecessary and distracting in a professionally published form. The booktabs package is useful for easily providing this professionalism in LaTeX tables, and the documentation also provides guidelines on what constitutes a "good" table.

In brief, the package uses for the uppermost rule (or line),  for the rules appearing in the middle of the table (such as under the header), and  for the lowermost rule. This ensures that the rule weight and spacing are acceptable. In addition, can be used for mid-rules that span specified columns. The following example contrasts the use of booktabs and two equivalent normal LaTeX implementations (the second example requires  or, and the third example requires  in the preamble).

Using
Usually the need arises for footnotes under a table (and not at the bottom of the page), with a caption properly spaced above the table. These are addressed by the ctable package. It provides the option of a short caption given to be inserted in the list of tables, instead of the actual caption (which may be quite long and inappropriate for the list of tables). The uses the  package.

Sideways tables
Tables can also be put on their side within a document using the or the  package. See the Rotations chapter.

Table with legend
To add a legend to a table the caption package can be used. With the caption package a statement can be added besides the normal. Example:

The normal caption is needed for labels and references.

The eqparbox package
On rare occasions, it might be necessary to stretch every row in a table to the natural width of its longest line, for instance when one has the same text in two languages and wishes to present these next to each other with lines synching up. A tabular environment helps control where lines should break, but cannot justify the text, which leads to ragged right edges. The package provides the command  which is like  but instead of a  argument, it takes a tag. During compilation it bookkeeps which with a certain tag contains the widest text and can stretch all es with the same tag to that width. Combined with the package, one can define a column specifier that justifies the text in all lines:comand

See the documentation of the package for more details.

The paracol package
The various tabular environments available for LaTeX are feature rich; however, they lack the ability to automatically page break large rows. The paracol package provides automatic page breaks in between rows and in certain cases can replace the tabular environment. Such situations could be common in documents that require translations and definitions, which may also includes lists.

For further detail see the documentation of the package.

Floating with table
In WYSIWYG document processors, it is common to put tables in the middle of the text. This is what we have been doing until now. Professional documents, however, often make it a point to print tables on a dedicated page so that they do not disrupt the flow. From the point of view of the source code, one has no idea on which page the current text is going to lie, so it is hardly possible to guess which page may be appropriate for our table. LaTeX can automate this task by abstracting objects such as tables, pictures, etc., and deciding for us where they might fit best. This abstraction is called a float. Generally, an object that is floated will appear in the vicinity of its introduction in the source file, but one can choose to control its position also.

To tell LaTeX we want to use our table as a float, we need to put a environment around the  environment, which is able to float and add a label and caption.

The environment initiates a type of float just as the environment. In fact, the two bear a lot of similarities (positioning, captions, etc.). More information about floating environments, captions etc. can be found in Floats, Figures and Captions.

The environment names may now seem quite confusing. Let's sum it up:
 * is for the content itself (columns, lines, etc.).
 * is for the location of the table on the document, plus caption and label support.

In the table, we used a label, so now we can refer to it just like any other reference:

The environment is also useful when you want to have a list of tables at the beginning or end of your document with the command

The captions now show up in the list of tables, if displayed.

You can set the optional parameter to define the position of the table, where it should be placed. The following characters are all possible placements. Using sequences of it define your "wishlist" to LaTeX.

Default is tbp, which means that it is by default placed on the top of the page. If that's not possible, it's placed at the bottom if possible, or finally with other floating environments on an extra page.

You can force LaTeX to use one given position. E.g. [!h] forces LaTeX to place it exactly where you place it (Except when it's really impossible, e.g you place a table here and this place would be the last line on a page). Again, understand it correctly: it urges LaTeX to put the table at a specific place, but it will not be placed there if LaTeX thinks it will not look great. If you really want to place your table manually, do not use the environment.

Centering the table horizontally works like everything else, using the command just after opening the  environment, or by enclosing it with a  environment.

Using spreadsheets and data analysis tools
For complex or dynamic tables, you may want to use a spreadsheet. You might save lots of time by building tables using specialized software and exporting them in LaTeX format. The following plugins and libraries are available for some popular software:
 * calc2latex: for LibreOffice and OpenOffice.org Calc spreadsheets,
 * excel2latex: for Microsoft Office Excel,
 * matrix2latex: for Python and MATLAB,
 * pandas: pandas DataFrame's have a method to convert data they contain to latex,
 * latex-tools: a Ruby library,
 * xtable: a library for R,
 * org-mode: for Emacs users, org-mode tables can be used inline in LaTeX documents, see for a tutorial.
 * Emacs align commands: the align commands can clean up a messy LaTeX table.
 * Online Table generator for LATeX: An online tool for creating simple tables within the browser. LaTeX format is directly generated as you type.
 * Create LaTeX tables online: Online tool.

However, copying the generated source code to your document is not convenient at all. For maximum flexibility, generate the source code to a separate file which you can input from your main document file with the command. If your spreadsheet supports command-line, you can generate your complete document (table included) in one command, using a Makefile for example.

See Modular Documents for more details.

Need more features?
Have a look at one of the following packages:

 * hhline:  do whatever you want with horizontal lines
 * array:   gives you more freedom on how to define columns
 * colortbl: make your table more colorful
 * threeparttable makes it possible to put footnotes both within the table and its caption
 * arydshln: creates dashed horizontal and vertical lines
 * <tt>ctable</tt>: allows for footnotes under table and properly spaced caption above (incorporates booktabs package)
 * <tt>slashbox</tt>: create 2D tables with the first cell containing a description for both axes. Not available in Tex Live 2011 or later.
 * <tt>diagbox</tt>: compatible to <tt>slashbox</tt>, come with Tex Live 2011 or later
 * <tt>dcolumn</tt>: decimal point alignment of numeric cells
 * <tt>rccol</tt>: advanced decimal point alignment of numeric cells with rounding
 * <tt>numprint</tt>: print numbers, in the current mode (text or math) in order to use the correct font, with separators, exponent and/or rounded to a given number of digits. tabular(*), array, tabularx, and longtable environments are supported using all features of numprint
 * <tt>spreadtab</tt>: spread sheets allowing the use of formulae
 * <tt>siunitx</tt>: alignment of tabular entries
 * <tt>pgfplotstable</tt>: loads, rounds, formats and postprocesses numerical tables, e.g. by importing the data directly from .csv (comma-separated value) files instead of manually writing the whole tables in LaTeX code. Programs such as Excel, LibreOffice Calc etc. can export data sheets as .csv files.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: LaTeX/Tables


text:
LaTeX/Importing Graphics

Importing external graphics
You can import external graphics using package . The most important command is . LaTeX itself treats the image like normal text, i.e. as a box of certain height and width.

The package documentation list the options  and , as well as others.

Using  several graphics formats are supported:,   and . Modern installations of LaTeX can use files as well, but indirectly.

LaTeX in -mode supports only -files.

You can align the images in a matrix. You just have to think of a proper width for the images.

Three images in one line, each image has a width of just 30 % of the available line width, centered with respect to the text below.

If you want to add a caption and let LaTeX keep track of the numbering, have a look at the floats section.

Converting graphics
You should also take a look at Export To Other Formats for other possibilities.
 * Note:

You can convert EPS to PDF with the epstopdf utility, included in package of the same name. This tool is actually called by pdflatex to convert EPS files to PDF in the background when the package is loaded. This process is completely invisible to the user.
 * epstopdf

You can batch convert files using the command-line. In Bourne Shell (Unix) this can be done by:

In Windows, multiple files can be converted by placing the following line in a batch file (a text file with a .bat extension) in the same directory as the images: which can then be run from the command line.

If produces a whole page with your small graphics somewhere on it, use or try using the ps2pdf utility which should be installed with Ghostscript (required for any TeX distribution). to crop the final PDF.

When all of the above fails, one can simplify the EPS file before attempting other conversions, by using the eps2eps tool (also see next section): This will convert all the fonts to pre-drawn images, which is sometimes desirable when submitting manuscripts for publication. However, on the downside, the fonts are NOT converted to lines, but instead to bitmaps, which reduces the quality of the fonts.
 * eps2eps

imgtops is a lightweight graphics utility for conversions between raster graphics (JPG, PNG, ...) and EPS/PS files.
 * imgtops

Inkscape can also convert files from and to several formats, either from the GUI or from the command-line. For instance, to obtain a PDF from a SVG image you can do: It is possible to run this from within a LaTeX file, the package (when running (pdf)latex with the --shell-escape option) can do this using Inkscape's pdf+tex export option, or a simple macro can be used. See [http://tex.stackexchange.com/q/2099/28808 How to include SVG diagrams in LaTeX? -- Stackexchange] See Export To Other Formats for more details.
 * Inkscape

To properly edit an EPS file, you can convert it to an editable format using pstoedit. For instance, to get an Xfig-editable file, do: And to get an SVG file (editable with any vector graphics tool like Inkscape) you can do: Sometimes pstoedit fails to create the target format (for example when the EPS file contains clipping information).
 * pstoedit

Under Windows, PDFCreator is an open source software that can create PDF as well as EPS files. It installs a virtual printer that can be accessed from other software having a "print..." entry in their menu (virtually any program).
 * PDFCreator

 * Raster graphics converters
 * Sam2p (convert) or
 * ImageMagick (convert) or
 * GraphicsMagick (gm convert).

These three programs operate much the same way, and can convert between most graphics formats. Sam2p however is the most recent of the three and seems to offer both the best quality and to result in the smallest files.

PNG alpha channel
Acrobat Reader sometimes has problems with displaying colors correctly if you include graphics in PNG format with alpha channel. You can solve this problem by dropping the alpha channel. On Linux it can be achieved with convert from the ImageMagick program:

Converting a color EPS to grayscale
Sometimes color EPS figures need to be converted to black-and-white or grayscale to meet publication requirements. This can be achieved with the eps2eps of the Ghostscript package and  programs:

Third-party graphics tools
We will not tackle the topic of procedural graphics created from within LaTeX code here (TikZ, PSTricks, MetaPost and friends). See Introducing Procedural Graphics for that.

You should prefer vector graphics over raster graphics for their quality. Raster graphics should only be used in case of photos. Diagrams of any sort should be vectors.

As we have seen before, LaTeX handles
 * EPS and PDF for vector graphics;
 * PNG and JPG for raster graphics.

If some tools cannot save in those formats, you may want to convert them before importing them.

Vector graphics
Dia is a cross platform diagramming utility which can export eps images, or generate tex drawn using the package.
 * Dia

 * Inkscape

Another program for creating vector graphics is Inkscape. It can run natively under Windows, Linux or Mac OS X (with X11). It works with Scalable Vector Graphics (SVG) files, although it can export to many formats that can be included in LaTeX files, such as EPS and PDF. From version 0.48, there is a combined PDF/EPS/PS+LaTeX output option, similar to that offered by Xfig. There are instructions on how to save your vector images in a PDF format understood by LaTeX and have LaTeX manage the text styles and sizes in the image automatically. . Today there is the which provides an  command to convert and include svg-graphics directly in your LaTeX document using Inkscape. You may have a look at this extended example too.

An extremely useful plug-in is textext, which can import LaTeX objects. This can be used for inserting mathematical notation or LaTeX fonts into graphics (which may then be imported into LaTeX documents).

 * Ipe

The Ipe extensible drawing editor is a free vector graphics editor for creating figures in PDF or EPS format. Unlike Xfig, Ipe represents LaTeX fonts in their correct size on the screen which makes it easier to place text labels at the right spot. Ipe also has various snapping modes (for example, snapping to points, lines, or intersections) that can be used for geometric constructions.

Yet another solution is provided by the packages, which allows TeX annotations to imported graphics. See Labels in the figures.
 * lpic

It is also possible to export vector graphics to EPS format using LibreOffice Draw, which is an open source office suite available for Windows, Linux and Mac.
 * LibreOffice

Vector editor TpX separates geometric objects from text objects. Geometric objects are saved into .PDF file, the rest is saved in .TpX file to be processed by LaTeX. User just create the graphics in TpX editor and calls the .TpX file from latex file by command  \input{...TpX}.
 * TpX

Xfig is a basic program that can produce vector graphics, which can be exported to LaTeX. It can be installed on Unix platforms.
 * Xfig

On Microsoft Windows systems, Xfig can only be installed using Cygwin-X; however, this will require a fast internet connection and about 2 gigabytes of space on your computer. With Cygwin, to run Xfig, you need to first start the "Start X - Server", then launch "xterm" to bring up a terminal. In this terminal type "xfig" (without the quotation marks) and press return.

Alternatively, WinFIG. WinFIG is an attempt to achieve the functionality of xfig on Windows computers.

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. <li> 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. <li> 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. <li> In your LaTeX document, where the picture should be, use the following, where "test" is replaced by the name of the image:

Observe that this is just like including a picture, except that rather than using <tt>\includegraphics</tt>, we use <tt>\input</tt>. If the export was into PS/LaTeX, the file extension to include would be .pstex_t instead of .pdf_t. <li> Make sure to include packages and  in the file, with the  command right below the  command, like this:

</ol> And you're done!

For more details on using xfig with LaTeX, this chapter of the xfig User Manual may prove helpful.

Commercial vector graphics software, such as Adobe Illustrator, CorelDRAW, and FreeHand are commonly used and can read and write EPS figures. However, these products are limited to Windows and Mac OS X platforms.
 * Other tools

Raster graphics
Photoshop can save to EPS.
 * Adobe Photoshop

GIMP, has a graphical user interface, and it is multi-platform. It can save to EPS and PDF.
 * GIMP

Plots and Charts
Generic Mapping Tools (GMT), maps and a wide range of highly customisable plots.
 * Generic Mapping Tools (GMT)

Gnumeric, spreadsheets has SVG, EPS, PDF export
 * Gnumeric

Gnuplot, producing scientific graphics since 1986. If you want to make mathematical plots, then Gnuplot can save in any format. You can get best results when used along PGF/TikZ.
 * Gnuplot

matplotlib, plotting library written in python, with PDF and EPS export. On the other hand there is a PGF export also. There are some tricks to be able to import formats other than EPS into your DVI document, but they're very complicated. On the other hand, converting any image to EPS is very simple, so it's not worth considering them.
 * matplotlib

R, statistical and scientific figures.
 * R

Editing EPS graphics
As described above, graphics content can be imported into LaTeX from outside programs as EPS files. But sometimes you want to edit or retouch these graphics files. An EPS file can be edited with any text editor since it is formatted as ASCII. In a text editor, you can achieve simple operations like replacing strings, changing the bounding box, or moving items slightly, but anything further becomes cumbersome. Vector graphics editors, like Inkscape, may also be able to import EPS files for subsequent editing. This approach also for easier editing. However, the importing process may occasionally modify the original EPS image.

title: LaTeX/Importing Graphics


text:
LaTeX/Floats, Figures and Captions

The previous chapter introduced importing graphics. However, just having a picture stuck in between paragraphs does not look professional. To start with, we want a way of adding captions, and to be able to cross-reference. What we need is a way of defining figures. It would also be good if LaTeX could apply principles similar to when it arranges text to look its best to arrange pictures as well. This is where floats come into play.

Floats
Floats are containers for things in a document that cannot be broken over a page. LaTeX by default recognizes "table" and "figure" floats, but you can define new ones of your own (see Custom floats below). Floats are there to deal with the problem of the object that won't fit on the present page and to help when you really don't want the object here just now.

Floats are not part of the normal stream of text, but separate entities, positioned in a part of the page to themselves (top, middle, bottom, left, right, or wherever the designer specifies). They always have a caption describing them and they are always numbered so they can be referred to from elsewhere in the text. LaTeX automatically floats Tables and Figures, depending on how much space is left on the page at the point that they are processed. If there is not enough room on the current page, the float is moved to the top of the next page. This can be changed by moving the Table or Figure definition to an earlier or later point in the text, or by adjusting some of the parameters which control automatic floating.

Authors sometimes have many floats occurring in rapid succession, which raises the problem of how they are supposed to fit on the page and still leave room for text. In this case, LaTeX stacks them all up and prints them together if possible, or leaves them to the end of the chapter in protest. The skill is to space them out within your text so that they intrude neither on the thread of your argument or discussion nor on the visual balance of the typeset pages.

As with various other entities, there exist limitations on the number of unprocessed (placed) floats in line. LaTeX by default can cope with maximum 18 floats and a symptomatic error is:

! LaTeX Error: Too many unprocessed floats.

The package lifts this limit.

Figures
To create a figure that floats, use the environment.

The previous section mentioned how floats are used to allow LaTeX to handle figures while maintaining the best possible presentation. However, there may be times when you disagree, and a typical example is with its positioning of figures. The placement specifier parameter exists as a compromise, and its purpose is to give the author a greater degree of control over where certain floats are placed.

What you do with these placement permissions is to list which of the options you wish to make available to LaTeX. These are simply possibilities, and LaTeX will decide when typesetting your document which of your supplied specifiers it thinks is best. Frank Mittelbach describes the algorithm :

 * If a float is encountered, LaTeX attempts to place it immediately according to its rules (detailed later)
 * If this succeeds, the float is placed and that decision is never changed;
 * If this does not succeed, then LaTeX places the float into a holding queue to be reconsidered when the next page is started (but not earlier).
 * Once a page has finished, LaTeX examines this holding queue and tries to empty it as best as possible. For this, it will first try to generate as many float pages as possible (in the hope of getting floats off the queue). Once this possibility is exhausted, it will next try to place the remaining floats into top and bottom areas. It looks at all the remaining floats and either places them or defers them to a later page (i.e., re-adding them to the holding queue once more).
 * After that, it starts processing document material for this page. In the process, it may encounter further floats.
 * If the end of the document has been reached or if a \clearpage is encountered, LaTeX starts a new page, relaxes all restrictive float conditions, and outputs all floats in the holding queue by placing them on float page(s).

In some special cases, LaTeX won't follow these positioning parameters and additional commands will be necessary, for example, if one needs to specify an alignment other than centered for a float that sits alone in one page.

Use to add a list of the figures in the beginning of the document. To change the name used in the caption from Figure to Example, use in the figure contents. See the New commands section for more information on this.

Figures with borders
It's possible to get a thin border around all figures. You have to write the following once at the beginning of the document:

The border will not include the caption.

Tables
Floating tables are covered in a separate chapter. Let's give a quick reminder here. The environment that was used to construct the tables is not a float by default. Therefore, for tables you wish to float, wrap the environment within a  environment, like this:

You may feel that it is a bit long-winded, but such distinctions are necessary, because you may not want all tables to be treated as a float.

Use to add a list of the tables in the beginning of the document.

Keeping floats in their place
The package provides the command, which can be used to prevent floats from being moved over it. This can, e.g., be useful at the beginning of each section. The package even provides an option to change the definition of to automatically include a. This can be set by loading the package with the option. may also be useful to prevent floats intruding on lists created using or.

The package can be used to force floats to appear after they are defined, and the  package can be used to place all floats at the end of a document.

The package provides the   option to floating environments, which completely stops them from floating.

Package provides the command  that lets you typeset a caption without a floating environment. You have the full and absolute control about the placement of your figures and captions.

Captions
It is always good practice to add a caption to any figure or table. Fortunately, this is very simple in LaTeX. All you need to do is use the command within the float environment. LaTeX will automatically keep track of the numbering of figures, so you do not need to include this within the caption text.

The location of the caption is traditionally underneath the float. However, it is up to you to, therefore, insert the caption command after the actual contents of the float (but still within the environment). If you place it before, then the caption will appear above the float. Try out the following example to demonstrate this effect:

Note that the command flips its content horizontally.

Side captions
It is sometimes desirable to have a caption appear on the side of a float, rather than above or below. The package can be used to place a caption beside a figure or table. The following example demonstrates this for a figure by using a environment in place of the  environment. The package is newer and has more capabilities.

Unnumbered captions
In some types of documents (such as presentations), it may not be desirable for figure captions to start with Figure:. This is easy to suppress by just placing the caption text in the  environment, without enclosing it in a. This however means that there is no caption available for inclusion in a list of figures.

Caption Setup Rename
In case you want to rename your table caption from "Table" to something else, you can use the command. For example,

\usepackage{caption} \captionsetup[table] {name=New Table Name}

Lists of figures and tables
Captions can be listed at the beginning of a paper or report in a "List of Tables" or a "List of Figures" section by using the or  commands, respectively. The caption used for each figure will appear in these lists, along with the figure numbers, and page numbers that they appear on.

The command also has an optional parameter,  which is used for the List of Tables or List of Figures. Typically the description is for the caption listing, and the  description will be placed beside the figure or table. This is particularly useful if the caption is long, and only a "one-liner" is desired in the figure/table listing. Here is an example of this usage:

Labels and cross-referencing
Labels and cross-references work fairly similarly to the general case - see the Labels and Cross-referencing section for more information.

If the label picks up the section or list number instead of the figure number, put the label inside the caption to ensure correct numbering. If you get an error when the label is inside the caption, use in front of the  command.

Wrapping text around figures
An author may prefer that some floats do not break the flow of text, but instead allow text to wrap around it. (Obviously, this effect only looks decent when the figure in question is significantly narrower than the text width.)

A word of warning: Wrapping figures in LaTeX will require a lot of manual adjustment of your document. There are several packages available for the task, but none of them work perfectly. Before you make the choice of including figures with text wrapping in your document, make sure you have considered all the options. For example, you could use a layout with two columns for your documents and have no text-wrapping at all.

Anyway, we will look at the package. Note that may not come with the default installation of LaTeX; you might need to install additional packages. Noted also, wrapfig is incompatible with the enumerate and itemize environments

To use, you must first add this to the preamble:

This then gives you access to:

The lineheight is expressed as the number of lines of text the figure spans. LaTeX will automatically calculate the value if this option is left blank but this can result in figures that look ugly (with too much spacing). The LaTeX calculation is manually overridden by entering the number of lines you would like the figure to span. This option can't be entered in pt, mm, etc...

There are overall eight possible positioning targets:

The uppercase-character allows the figure to float, while the lowercase version means "exactly here".

The overhang of the figure can be manually set using the overhang option in pt, cm, etc...

The width is, of course, the width of the figure. An example:

You can also allow LaTeX to assign a width to the wrap by setting the width to 0pt:

Note that we have specified a size for both the environment and the image we have included. We did it in terms of the text width: it is always better to use relative sizes in LaTeX, let LaTeX do the work for you! The "wrap" is slightly bigger than the picture, so the compiler will not return any strange warning and you will have a small white frame between the image and the surrounding text. You can change it to get a better result, but if you don't keep the image smaller than the "wrap", you will see the image over the text.

The wrapfig package can also be used with user-defined floats with float package. See below in the section on custom floats.

Tip for figures with too much white space
You can use parameter to control additional space above and below the figure:

To control the horizontal space between the image and the text, use the parameter.

It happens that you'll generate figures with too much (or too little) white space on the top or bottom. In such a case, you can simply make use of the optional argument. It specifies the height of the figure in the number of lines of text. Also remember that the environment adds some extra white space at its top and bottom; consider using the command  instead.

Another possibility is adding space within the float using the command. The argument is the size of the space you want to add, you can use any unit you want, including pt, mm, in, etc. If you provide a negative argument, it will add a negative space, thus removing some white space. Using tends to move the caption relative to the float while the  argument does not. Here is an example using the command, the code is exactly the one of the previous cases, we just added some negative vertical spaces to shrink everything up:

In this case, it may look too shrunk, but you can manage spaces the way you like. In general, it is best not to add any space at all: let LaTeX do the formatting work!

(In this case, the problem is the use of to center the image. The  environment adds extra space that can be avoided if  is used instead.)

Alternatively, you might use the package instead of the wrapfig package which produces a correct version without the excess white space out of the box without any hand-tuning.

There is also an alternative to : the package.

To remove the white space from a figure once for all, one should refer to the program pdfcrop, included in most TeX installations.

Subfloats
A useful extension is the package, which uses subfloats within a single float. The package ( package is deprecated ) is a useful alternative when used in conjunction with LaTeX templates (i.e. templates for journals from Springer and IOP, IEEETran and ACM SIG) that are not compatible with. These packages give the author the ability to have subfigures within figures, or subtables within table floats. Subfloats have their own caption, and an optional global caption. An example will best illustrate the usage of the package:

You will notice that the figure environment is set up as usual. You may also use a table environment for subtables. For each subfloat, you need to use:

If you intend to cross-reference any of the subfloats, see where the label is inserted; outside the -environment will provide the global caption.

will arrange the figures or tables side-by-side providing they can fit, otherwise, it will automatically shift subfloats below. This effect can be added manually, by putting the newline command before the figure you wish to move to a newline.

Horizontal spaces between figures are controlled by one of several commands, which are placed in between and :
 * A non-breaking space (specified by ~ as in the example above) can be used to insert a space in between the subfigs.
 * Math spaces:, , , and
 * Generic space:
 * Automatically expanding/contracting space:

Figures in multiple parts
Sometimes you need to divide up a figure over multiple floats, for instance because the figure is too big to fit on one page. In this case you can use continued figures using the  package.

Put this in your preamble:

Then you can use continued floats as follows.

Wide figures in two-column documents
If you are writing a document using two columns (i.e. you started your document with something like ), you might have noticed that you can't use floating elements that are wider than the width of a column (using a LaTeX notation, wider than ), otherwise you will see the image overlapping with text. If you really have to use such wide elements, the only solution is to use the "starred" variants of the floating environments, that are and. Those "starred" versions work like the standard ones, but they will be as wide as the page, so you will get no overlapping.

A bad point of those environments is that they can be placed only at the top of the page or on their own page. If you try to specify their position using modifiers like b or h, they will be ignored. Add to the preamble in order to alleviate this problem with regard to placing these floats at the bottom of a page, using the optional specifier. Default is. However, h still does not work.

Custom floats
If tables and figures are not adequate for your needs, then you always have the option to create your own! Examples of such instances could be source code examples, or maps. For a program float example, one might therefore wish to create a float named. The package is your friend for this task. All commands to set up the new float must be placed in the preamble, and not within the document.

 * 1) Add  to the preamble of your document
 * 2) Declare your new float using:, where:
 * 3) * type - the new name you wish to call your float, in this instance, 'program'.
 * 4) * placement - t, b, p, or h (as previously described in Placement), where letters enumerate permitted placements.
 * 5) * ext - the file name extension of an auxiliary file for the list of figures (or whatever). LaTeX writes the captions to this file.
 * 6) * outer counter - the presence of this parameter indicates that the counter associated with this new float should depend on outer counter, for example 'chapter'.
 * 7) The default name that appears at the start of the caption is the type. If you wish to alter this, use
 * 8) Changing float style can be issued with  (Works on all subsequent  commands, therefore, must be inserted before  to be effective).
 * 9) * - the normal style for LaTeX floats, but the caption is always below the content.
 * 10) * - the normal style for LaTeX floats, but the caption is always above the content.
 * 11) * - a box is drawn that surrounds the float, and the caption is printed below.
 * 12) * - the caption appears above the float, with rules immediately above and below. Then the float contents, followed by a final horizontal rule.

Float styles can also be customized as the second example below illustrates.

An example document using a new float type:

The is an environment already discussed in Special paragraphs. It is good for source code, but if you want to introduce a lot of code you might consider using the package described in Source Code Listings, that was made just for it.

While this is useful, one should be careful when embedding the float within another float. In particular, the error not in outer par mode may occur. One solution might be to use the [H] option (not any other) on the inner float, as this option "pins" the inner float to the outer one.

Newly created floats with can also be used in combination with the  package from above. E.g. the following code creates a floating text box, which floats in the text on the right side of the page and is complete with caption, numbering, an index file with the extension .lob and a customization of the float's visual layout:

Caption styles
To change the appearance of captions, use the  package. For example, to make all caption labels small and bold:

The KOMA script packages have their own caption customizing features with e.g.,  and. However these definitions have limited effect on newly created float environments with the package.

Alternatively, you can redefine the command:

See this page for more information on counters. Finally, note that the package has long been deprecated.

Labels in the figures
There is a LaTeX package  to put LaTeX on top of included graphics, thus allowing to add TeX annotations to imported graphics. It defines a convenient interface to put TeX over included graphics, and allows for drawing a white background under the typeset material to overshadow the graphics. It is a better alternative for labels inside of graphics; you do not have to change text size when rescaling pictures, and all LaTeX power is available for labels.

A very similar package, with somewhat different syntax, is. The link given also points to the packages and.

A much more complicated package which can be used in the same way is TikZ. TikZ is a front-end to a drawing library called pgf (which is used to make beamer for instance). It can be used to label figures by adding text nodes on top of an image node.

Summary
That concludes all the fundamentals of floats. You will hopefully see how much easier it is to let LaTeX do all the hard work and tweak the page layouts in order to get your figures in the best place. As always, the fact that LaTeX takes care of all caption and reference numbering is a great time saver.

title: LaTeX/Floats, Figures and Captions