Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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}
  \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}
  \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} 
@i3v
Copy link

i3v commented Aug 22, 2018

Thanks for the great example!
I've noticed a tiny issue with in it though - please take a look at this.
It would be very nice, if you would be able to fix your code here and in your tex.stackexchange.com answer, so that noone would have a chance to ran into this any more :).

@rbnvrw
Copy link
Author

rbnvrw commented Sep 4, 2018

Thank you @i3v, I've updated the code! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment