Skip to content

Instantly share code, notes, and snippets.

@anthony-wang
Forked from rbnvrw/LaTeXScaleBars.md
Created July 1, 2017 17:11
Show Gist options
  • Save anthony-wang/9287078ebd1230c0c2c7721ac894e30e to your computer and use it in GitHub Desktop.
Save anthony-wang/9287078ebd1230c0c2c7721ac894e30e to your computer and use it in GitHub Desktop.
Adding scalebars to images in LaTeX

Scalebar with background

Scalebar with background

To change the backgroundcolor, adjust the scalebgcolor variable to use the desired color. Add the following code to your preamble:

\usepackage{tikz}
\usepackage[usenames, dvipsnames]{color}
\definecolor{scalebgcolor}{rgb}{0.08,0.52,0.80}

\newcommand{\scalebarbackground}[5][white]{
 \begin{tikzpicture}
  \draw (0,0) node[anchor=south west,inner sep=0] (image) { #2 };
  \begin{scope}[x={(image.south east)},y={(image.north west)}]
   \fill [fill=scalebgcolor, fill opacity=0.5] (0.04,1.3em) rectangle (#5*#4/#3+0.04,0.1em);
   \draw [#1, line width=0.2em] (0.04,1.2em) -- node[below,inner sep=0.1em, font=\footnotesize] {\SI{#5}{\micro \meter}} (#5*#4/#3+0.04,1.2em);
  \end{scope}
 \end{tikzpicture}
}

Usage:

\scalebarbackground{\includegraphics[width=\linewidth]{image.png}}{1186}{9.887}{15} 

Scalebar without background

Scalebar without background

Add the following code to your preamble:

\usepackage{tikz}
\usepackage[usenames, dvipsnames]{color}

% Inserts a scale bar into an image
% Optional argument 1: the colour of the bar and text
% Argument 2: an \includegraphics command
% Argument 3: the real world width of the image
% Argument 4: the length of the scale bar in pixels
% Argument 5: the length of the scale bar in um
\newcommand{\scalebar}[5][white]{
 \begin{tikzpicture}
  \draw (0,0) node[anchor=south west,inner sep=0] (image) { #2 };
  \begin{scope}[x={(image.south east)},y={(image.north west)}]
   \draw [#1, line width=0.2em] (0.04,1.2em) -- node[below,inner sep=0.1em, font=\footnotesize] {\SI{#5}{\micro \meter}} (#5*#4/#3+0.04,1.2em);
  \end{scope}
 \end{tikzpicture}
}

Usage:

\scalebar{\includegraphics[width=\linewidth]{image.png}}{1186}{9.887}{15} 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment