2
$\begingroup$

On Mathematica 13 or later version, the ChemicalFormula and ChemicalReaction functions helpe a lot to deal with chemical formula in Mathematica, but there are still a lot limits as compared to the Chemmacros of LaTeX.

For example, if there is need to make plot label to as it is in LaTeX:

$$\ch{H2O}=\ch{H2}+\ch{O2}$$

How should I do? I tried to do this in Mathematica:

Plot[Sin[x], {x, 1, 5}, 
 PlotLabel -> 
  ChemicalFormula["H2O"]["Formula"] <> "=" <> 
   ChemicalFormula["H2"]["Formula"] <> "+" <> 
   ChemicalFormula["O2"]["Formula"]]

But the output is

enter image description here

Deleting the <> will cause this wrong output:

enter image description here

Of course, they are all wrong.

$\endgroup$
2
  • $\begingroup$ Could you show full latex code which makes your latex works? Using \usepackage{chemmacros} it gives errors. So I used mhchem $\endgroup$
    – Nasser
    Commented Jun 3, 2023 at 3:11
  • $\begingroup$ @Nasser Thanks for your reply. \ce should be \ch, and I changed them now. $\endgroup$
    – Y. zeng
    Commented Jun 3, 2023 at 3:21

1 Answer 1

4
$\begingroup$

Either do

lbl = Style[
   Row[{ChemicalFormula["H2O"]["Formula"], " = ", 
     ChemicalFormula["H2"]["Formula"], " + ", 
     ChemicalFormula["O2"]["Formula"]}], 20];

Plot[Sin[x], {x, 1, 5}, PlotLabel -> lbl]

Mathematica graphics

Or better

Needs["MaTeX`"]

SetOptions[MaTeX,"Preamble"->{"\\usepackage{mhchem,upgreek}"}];
lbl=MaTeX["\ce{H2O}=\ce{H2}+\ce{O2}",Magnification->2];
Plot[Sin[x],{x,1,5},PlotLabel->lbl]

Mathematica graphics

Update

For ch instead of ce then do

Needs["MaTeX`"]
SetOptions[MaTeX, "Preamble" -> {"\\usepackage{chemmacros}"}];
lbl = MaTeX["\\ch{H2O}=\\ch{H2}+\\ch{O2}", Magnification -> 2];
Plot[Sin[x], {x, 1, 5}, PlotLabel -> lbl]

Mathematica graphics

$\endgroup$
4
  • $\begingroup$ As your second way, when I ran it, there is Cannot open MaTeX ` What is the MaTeX and how do you know you can run it in Mathematica? Thanks $\endgroup$
    – Y. zeng
    Commented Jun 3, 2023 at 3:18
  • $\begingroup$ @Y.zeng Matex is a package. You need to install it first. see MaTeXInstall it assumes you have a TeX also installed on your system. See instructions for MaTeX what it needs. $\endgroup$
    – Nasser
    Commented Jun 3, 2023 at 3:20
  • $\begingroup$ Thanks. I can run the second code now. It is really good. $\endgroup$
    – Y. zeng
    Commented Jun 3, 2023 at 5:34
  • $\begingroup$ The output from MaTeX is a graphic. So the first way may be better as they are characters which can be copied if exported as a format of PDF. $\endgroup$
    – Y. zeng
    Commented Jun 3, 2023 at 6:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.