Math operator in specifying figure width in LaTeX
-
05-07-2019 - |
Question
In LaTeX figures, one can use \textwidth
and \columnwidth
to specify sizes of the graphic relative to the size of surrounding text, e.g.
\includegraphics[width=.5\textwidth]{myimage}
.
I would like to easily switch from onecolumn to twocolumn template (and back) without the figure growing too large for onecolumn template. For twocolumn template (where \columnwidth
is roughly half the \textwidth
), I would like to have something like:
\includegraphics[width=.9\columnwidth]{myimage}
.
and for onecolumn template (where \columnwidth
and \textwidth
are equal):
\includegraphics[width=.5\textwidth]{myimage}
.
Now, I figured I could limit this using some kind of a min operator:
\includegraphics[width=min(.5\textwidth,.9\columnwidth)]{myimage}
but this is invalid syntax. Is there something like this to solve this problem, possibly through the use of LaTeX macro system?
Solution
Although it's possible to write this sort of macro, I wouldn't want to hardcode it into each figure; how about something like this
\makeatletter
\newlength \figwidth
\if@twocolumn
\setlength \figwidth {0.9\columnwidth}
\else
\setlength \figwidth {0.5\textwidth}
\fi
\makeatother
and then use
\includegraphics[width=\figwidth]{myimage}
to insert the graphic.
OTHER TIPS
\textwidth
is the horizontal width of the page body and not really appropriate for your purposes.
\linewidth
is the width of the current line; it will be updated appropriate to columns, indentation, etc.
The following paragraph produces a picture that should precisely fit the entire line width (i.e. no overful warning):
\noindent\includegraphics[width=\linewidth]{myimage}
If you prefer small margins on the left and right, you can use:
\begin{center}
\includegraphics[width=.9\linewidth]{myimage}
\end{center}
Or, if you want to specify the margins in an absolute size:
\usepackage{calc}
...
\begin{center}
\includegraphics[width=\linewidth-20pt]{myimage}
\end{center}
Hmm... the code above (\if@twocolumn etc.) is not working for me at all. No idea why not. :( tetex on osX using fink. Trying to use revtex4, so perhaps that's the problem. I really like the idea of this type of change because I'm going to be dorking with widths etc. for my thesis and various journal articles, and to have these distances specified with a macro may be helpful for these types of conversions.
Any comments greatly appreciated! -Allen
Somebody else who is more familiar with this will probably answer, but note that you would also need to change your figure type to be figure* if you are going two-column.