[Tex/LaTex] Change math font for figures only (including TikZ environments within figures)

fontsmath-modesans-seriftikz-pgf

In my document, I want the main text to be in the times font, and the math to be in the txfonts font. This I can do with the help of the txfonts package. However, I want everything that shows up in my figures to be sans serif, including the math. So far I've been able to change the text font to sans serif but I also want to change the math font to a sans serif, both in the caption and the figure itself (where I use TikZ).

Here's a minimal (non-working) example that needs tweaking. The problem is the math within the figure and the caption which now is txfonts.

\documentclass{article}
\usepackage{tikz}
%This package is used to get sans serif for regular text in captions.
\usepackage[font=sf]{caption}
%This package is used to get times for the main text and txfonts for math.
\usepackage[varg]{txfonts}
\begin{document}
Main text is supposed to be times. Math in main text is supposed to be     txfonts: $1+1=3$.
\begin{figure}
%Here I invoke the font option to make text within TikZ sans serif.
\begin{tikzpicture}[font=\sffamily]
\node at (0,0) {Sans Serif}; 
\node at (0,1) {Sans Serif Math: $5=3$}; 
\end{tikzpicture}
\caption{Figure caption text is supposed to be sans serif. Math in figure   capture text is supposed to be sans serif: $3+1=4.5$.}
\end{figure}
\end{document}

Best Answer

You can use the sansmath package in conjunction the float and everyhook packages to change the math within the figures only. This solution inherits all of the problems associated with sans math as implemented by the sansmath package. (See its documentation for details.)

\documentclass{article}
\usepackage{tikz}
%This package is used to get sans serif for regular text in captions.
\usepackage[font=sf]{caption}
%This package is used to get times for the main text and txfonts for math.
\usepackage[varg]{txfonts}
\usepackage{float} % to easily modify floats
\usepackage{etoolbox} % nice command patching
\usepackage{sansmath} % sans serif math
\usepackage{everyhook} % nice \every... patching
% restyle figures to make \everymath=\sansmath (float package)
\restylefloat{figure}
\floatevery{figure}{\PushPreHook{math}{\sansmath}}
% undo the change to \everymath at the end of the figure (etoolbox)
\apptocmd{\endfigure}{\PopPreHook{math}}{}{}

\begin{document}
Main text is supposed to be times. Math in main text is supposed to be     txfonts: $1+1=3$.
\begin{figure}[h]
%Here I invoke the font option to make text within TikZ sans serif.
\begin{tikzpicture}[font=\sffamily]

\node[draw] at (0,0) {Sans Serif}; 
\node[draw] at (0,1) {Sans Serif Math: $5=3$}; 
\end{tikzpicture}
\caption{Figure caption text is supposed to be sans serif. 
 Math in figure   caption text is supposed to be sans serif: $3+1=4.5$.}
\end{figure}

This is some math after the figure $3 + 2 = 5$. It is back to serifs.
\end{document}

output of code

Related Question