[Tex/LaTex] Simpler way to add color to equations in math mode

colorfractionsmath-mode

I was looking for a simpler way to add color to math mode. Specifically, I wanted different parts of an equation to have different colors in order to better correlate with colors in a figure. The only thing I could find that worked was using \begingroup and \group. While the code below worked, I was wondering if someone had a simpler way of doing it. I couldn't find anything else looking around…

\usepackage[usenames, dvipsnames]{color}
\definecolor{myred1}{RGB}{255, 0, 0}
\definecolor{myyellow1}{RGB}{255, 255, 219}
\definecolor{mygreen1}{RGB}{0, 255, 0}
\definecolor{mygreen2}{RGB}{0, 126, 0}
\definecolor{myblue1}{RGB}{0, 0, 255}

\begin{equation}
\frac{
\begingroup
\textcolor{myblue1} 
{a}
\endgroup
}
{
\begingroup 
\textcolor{myred1} 
{b}
\endgroup
}
=
\frac{
\begingroup
\textcolor{mygreen2} 
{a + b}
\endgroup
}
{
\begingroup 
\textcolor{myblue1} 
{a}
\endgroup
}
\end{equation}

Best Answer

You need no \begingroup and \endgroup:

\documentclass{article}
\usepackage[usenames, dvipsnames]{color}

\definecolor{myred1}{RGB}{255, 0, 0}
\definecolor{myyellow1}{RGB}{255, 255, 219}
\definecolor{mygreen1}{RGB}{0, 255, 0}
\definecolor{mygreen2}{RGB}{0, 126, 0}
\definecolor{myblue1}{RGB}{0, 0, 255}

\begin{document}

\begin{equation}
\frac{\textcolor{myblue1}{a}}{\textcolor{myred1}{b}}
=
\frac{\textcolor{mygreen2}{a + b}}{\textcolor{myblue1}{a}}
\end{equation}

\end{document}

enter image description here

A possibly better interface with xparse:

\documentclass{article}
\usepackage{xparse}
\usepackage[usenames, dvipsnames]{color}

\ExplSyntaxOn
\NewDocumentCommand{\colorfrac}{O{}mm}
 {
  \group_begin:
  \keys_set:nn { khanna/colorfrac} { #1 }
  \frac
   {
    \textcolor{\l_khanna_colorfrac_num_tl}{#2}
   }
   {
    \textcolor{\l_khanna_colorfrac_den_tl}{#3}
   }
  \group_end:
 }
\keys_define:nn { khanna/colorfrac }
 {
  num .tl_set:N  = \l_khanna_colorfrac_num_tl,
  den .tl_set:N  = \l_khanna_colorfrac_den_tl,
  num .initial:n = black,
  den .initial:n = black,
 }
\ExplSyntaxOff

\definecolor{myred1}{RGB}{255, 0, 0}
\definecolor{myyellow1}{RGB}{255, 255, 219}
\definecolor{mygreen1}{RGB}{0, 255, 0}
\definecolor{mygreen2}{RGB}{0, 126, 0}
\definecolor{myblue1}{RGB}{0, 0, 255}

\begin{document}

\begin{equation}
\colorfrac[num=myblue1,den=myred1]{a}{b}
=
\colorfrac[num=mygreen2,den=myblue1]{a + b}{a}
\end{equation}

\end{document}