21

I'm trying to create a figure in matplotlib to insert in my LaTeX document, and I need the bold 'i' and 'j' symbols without their dots and a hat instead.

I've been using the code \mathbf{\hat{\textnormal{\bfseries\i}}} in my document, but as this uses the amsmath package (or possibly the amssymb package, sorry I don't know I am very new to both LaTeX and matplotlib) I cannot use it in the matplotlib label.

Hence I would love to know how to use LaTeX in matplotlib and how to write a preamble to install the package needed to use these symbols. I hope this makes sense, and I know this is probably already out there or is simple but I'm new so please dont get angry!

Thank you guys!

Edit

So I have somehow managed to get this far with the coding, but when ever I run the code, my python kernel crashes. Unfortunately I don't really understand my code or where it is going wrong, so have uploaded it in case it helps. Sorry for the long upload. Again thanks in advance!

from mpl_toolkits.mplot3d import Axes3D
import numpy, matplotlib, matplotlib.pyplot as pyplot

matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [
    r'\usepackage{amsmath}',
    r'\usepackage{amssymb}']
matplotlib.rcParams['font.family'] = 'serif'
matplotlib.rcParams['font.serif'] = 'Computer Modern'
matplotlib.verbose.level = 'debug-annoying'

Module_Colour = '#F0AE1E'

fig = pyplot.figure()
ax = fig.add_subplot(111, projection='3d')

X_arr = numpy.array([1.0,0.0,0.0])
Y_arr = numpy.array([0.0,1.0,0.0])
Z_arr = numpy.array([0.0,0.0,1.0])
O_arr = numpy.array([0.0,0.0,0.0])

pyplot.quiver(O_arr,O_arr,O_arr,X_arr,Y_arr,Z_arr,
              pivot='tail', length=1.0, linewidth=2.5,
              color = Module_Colour)

ax.set_xlabel('x-axis', fontsize=12.5)
ax.set_ylabel('y-axis', fontsize=12.5)
ax.set_zlabel('z-axis', fontsize=12.5)

ax.text(1.03, 0, 0, r'$\mathbf{\hat{\textnormal{\bfseries \i}}}$',
        fontsize=25, color = Module_Colour)
ax.text(0, 1.03, 0, r'$\mathbf{\hat{\textnormal{\bfseries \j}}}$',
        fontsize=25, color = Module_Colour)
ax.text(0, 0, 1.03, r'$\mathbf{\hat{\textnormal{\bfseries k}}}$',
        fontsize=25, color = Module_Colour)

ax.set_xlim3d([0, 1.05])
ax.set_ylim3d([0, 1.05])
ax.set_zlim3d([0, 1.13])
ax.view_init(elev=17.0, azim=44.0)

pyplot.savefig('file/pathway/figure.jpeg',
               bbox_inches='tight')
pyplot.show()

Edit

The debug error was:

FigureCanvasAgg.draw
RendererAgg.__init__
RendererAgg.__init__ width=800.0, height=600.0
RendererAgg.__init__ _RendererAgg done
RendererAgg.__init__ done
No LaTeX-compatible font found for the monospace font family in rcParams. Using default.
RendererAgg.points_to_pixels
No LaTeX-compatible font found for the monospace font family in rcParams. Using default.
C: && cd "C:\Users\alexd\.matplotlib\tex.cache" && latex -interaction=nonstopmode 8160df9e5349057f736eef7cf8779b4d.tex > "C:\Users\alexd\.matplotlib\tex.cache\8160df9e5349057f736eef7cf8779b4d.output"
This is pdfTeX, Version 3.14159265-2.6-1.40.17 (MiKTeX 2.9.6100 64-bit)
entering extended mode
(8160df9e5349057f736eef7cf8779b4d.tex
LaTeX2e <2016/03/31> patch level 3
Babel <3.9r> and hyphenation patterns for 75 language(s) loaded.
("C:\Program Files\MiKTeX 2.9\tex\latex\base\article.cls"
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
("C:\Program Files\MiKTeX 2.9\tex\latex\base\size10.clo"))
("C:\Program Files\MiKTeX 2.9\tex\latex\type1cm\type1cm.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\psnfss\helvet.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics\keyval.sty"))
("C:\Program Files\MiKTeX 2.9\tex\latex\psnfss\courier.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\base\textcomp.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\base\ts1enc.def"))
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsmath.sty"
For additional information on amsmath, use the `?' option.
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amstext.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsgen.sty"))
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsbsy.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsopn.sty"))
("C:\Program Files\MiKTeX 2.9\tex\latex\amsfonts\amssymb.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\amsfonts\amsfonts.sty"))
("C:\Program Files\MiKTeX 2.9\tex\latex\geometry\geometry.sty"
("C:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\ifpdf.sty")
("C:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\ifvtex.sty")
("C:\Program Files\MiKTeX 2.9\tex\generic\ifxetex\ifxetex.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\geometry\geometry.cfg")

Package geometry Warning: Over-specification in `h'-direction.
    `width' (5058.9pt) is ignored.

Package geometry Warning: Over-specification in `v'-direction.
    `height' (5058.9pt) is ignored.

)
No file 8160df9e5349057f736eef7cf8779b4d.aux.
("C:\Program Files\MiKTeX 2.9\tex\latex\base\ts1cmr.fd")
*geometry* driver: auto-detecting
*geometry* detected driver: dvips
[1] (8160df9e5349057f736eef7cf8779b4d.aux) )
Output written on 8160df9e5349057f736eef7cf8779b4d.dvi (1 page, 240 bytes).
Transcript written on 8160df9e5349057f736eef7cf8779b4d.log.

Dvi: C:\Users\alexd\.matplotlib\tex.cache\8160df9e5349057f736eef7cf8779b4d.dvi
Dvi._xxx: encountered special: papersize=5203.43999pt,5203.43999pt
find_tex_file(cmr12.tfm): [u'kpsewhich', u'cmr12.tfm']
find_tex_file result: C:/Program Files/MiKTeX 2.9/fonts/tfm/public/cm/cmr12.tfm
opening tfm file C:/Program Files/MiKTeX 2.9/fonts/tfm/public/cm/cmr12.tfm
lh=18, bc=0, ec=127, nw=34, nh=16, nd=10
find_tex_file(cmr12.vf): [u'kpsewhich', u'cmr12.vf']
find_tex_file result:
RendererAgg.points_to_pixels
C: && cd "C:\Users\alexd\.matplotlib\tex.cache" && latex -interaction=nonstopmode 27047192dde3a3a7381bad7b27d0fcb3.tex > "C:\Users\alexd\.matplotlib\tex.cache\27047192dde3a3a7381bad7b27d0fcb3.output"
This is pdfTeX, Version 3.14159265-2.6-1.40.17 (MiKTeX 2.9.6100 64-bit)
entering extended mode
(27047192dde3a3a7381bad7b27d0fcb3.tex
LaTeX2e <2016/03/31> patch level 3
Babel <3.9r> and hyphenation patterns for 75 language(s) loaded.
("C:\Program Files\MiKTeX 2.9\tex\latex\base\article.cls"
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
("C:\Program Files\MiKTeX 2.9\tex\latex\base\size10.clo"))
("C:\Program Files\MiKTeX 2.9\tex\latex\type1cm\type1cm.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\psnfss\helvet.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics\keyval.sty"))
("C:\Program Files\MiKTeX 2.9\tex\latex\psnfss\courier.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\base\textcomp.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\base\ts1enc.def"))
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsmath.sty"
For additional information on amsmath, use the `?' option.
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amstext.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsgen.sty"))
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsbsy.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsopn.sty"))
("C:\Program Files\MiKTeX 2.9\tex\latex\amsfonts\amssymb.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\amsfonts\amsfonts.sty"))
("C:\Program Files\MiKTeX 2.9\tex\latex\geometry\geometry.sty"
("C:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\ifpdf.sty")
("C:\Program Files\MiKTeX 2.9\tex\generic\oberdiek\ifvtex.sty")
("C:\Program Files\MiKTeX 2.9\tex\generic\ifxetex\ifxetex.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\geometry\geometry.cfg")

Package geometry Warning: Over-specification in `h'-direction.
    `width' (5058.9pt) is ignored.


Package geometry Warning: Over-specification in `v'-direction.
    `height' (5058.9pt) is ignored.

)
No file 27047192dde3a3a7381bad7b27d0fcb3.aux.
("C:\Program Files\MiKTeX 2.9\tex\latex\base\ts1cmr.fd")
*geometry* driver: auto-detecting
*geometry* detected driver: dvips
[1] (27047192dde3a3a7381bad7b27d0fcb3.aux) )
Output written on 27047192dde3a3a7381bad7b27d0fcb3.dvi (1 page, 288 bytes).
Transcript written on 27047192dde3a3a7381bad7b27d0fcb3.log.

Dvi: C:\Users\alexd\.matplotlib\tex.cache\27047192dde3a3a7381bad7b27d0fcb3.dvi
Dvi._xxx: encountered special: papersize=5203.43999pt,5203.43999pt
find_tex_file(cmmi12.tfm): [u'kpsewhich', u'cmmi12.tfm']
find_tex_file result: C:/Program Files/MiKTeX 2.9/fonts/tfm/public/cm/cmmi12.tfm
opening tfm file C:/Program Files/MiKTeX 2.9/fonts/tfm/public/cm/cmmi12.tfm
lh=18, bc=0, ec=127, nw=97, nh=15, nd=9
find_tex_file(cmmi12.vf): [u'kpsewhich', u'cmmi12.vf']
find_tex_file result:
C: && cd "C:\Users\alexd\.matplotlib\tex.cache" && dvipng -bg Transparent -D 100.0 -T tight -o "da3e0f170d11553ae39831280c346c0f.png" "27047192dde3a3a7381bad7b27d0fcb3.dvi" > "C:\Users\alexd\.matplotlib\tex.cache\da3e0f170d11553ae39831280c346c0f.output"
This is dvipng 1.15 Copyright 2002-2015 Jan-Ake Larsson
[1]

Then python.exe stops responding, and unfortunately I'm not very tech savvy so struggle to understand why this is happening.

Aldahunter
  • 618
  • 1
  • 6
  • 12
  • 1
    Look answers on this question http://stackoverflow.com/questions/2537868/sans-serif-math-with-latex-in-matplotlib/20709149#20709149 – Serenity Jan 03 '17 at 22:46
  • Hey @Serenity thank you for the help, I tried using those lines of coding but `Python` always seemed to crash. However @JimParker 's code (below) seems to work, but throws up an error! Sorry if I seem inept (I probably am), just have a very basic understanding of the both `LaTeX` and `Python` (`matplotlib`) – Aldahunter Jan 04 '17 at 15:03

2 Answers2

36

When I need to use LaTeX with matplotlib, I add the following to the python script (+ additional commands for debug info)

 import matplotlib.pyplot as plt

 plt.rc('text', usetex=True)
 plt.rc('text.latex', preamble=r'\usepackage{amsmath}
          \usepackage{foo-name} `...')
 matplotlib.verbose.level = 'debug-annoying'

commands to make your plot here

Jim Parker
  • 1,095
  • 11
  • 16
  • Okay wicked this is great, the Python Kernel doesn't crash now, but it does throw up an error of an Emergency stop. I'm not sure if this is how you're meant to do it but the error given is: `LaTeX was not able to process the following string: 'lp' Here is the full report generated by LaTeX: This is pdfTeX, Version 3.14159265-2.6-1.40.17 (MiKTeX 2.9.6100 64-bit) entering extended mode (372e60d9e5b5eecc85352d732bcaea1b.tex LaTeX2e <2016/03/31> patch level 3 Babel <3.9r> and hyphenation patterns for 75 language(s) loaded.` – Aldahunter Jan 04 '17 at 14:55
  • the rest: `("C:\Program Files\MiKTeX 2.9\tex\latex\base\article.cls" Document Class: article 2014/09/29 v1.4h Standard LaTeX document class ("C:\Program Files\MiKTeX 2.9\tex\latex\base\size10.clo")) ("C:\Program Files\MiKTeX 2.9\tex\latex\type1cm\type1cm.sty") ("C:\Program Files\MiKTeX 2.9\tex\latex\psnfss\helvet.sty" ("C:\Program Files\MiKTeX 2.9\tex\latex\graphics\keyval.sty")) ("C:\Program Files\MiKTeX 2.9\tex\latex\psnfss\courier.sty") ("C:\Program Files\MiKTeX 2.9\tex\latex\base\textcomp.sty" ("C:\Program Files\MiKTeX 2.9\tex\latex\base\ts1enc.def"))` – Aldahunter Jan 04 '17 at 14:58
  • and: `! LaTeX Error: File `<.sty' not found. Type X to quit or to proceed, or enter new name. (Default extension: sty) Enter file name: ! Emergency stop. l.8 \usepackage \usepackage No pages of output. Transcript written on 372e60d9e5b5eecc85352d732bcaea1b.log.` Sorry about the long comments, just wasn't sure what was important within the error. Thank you for the help! – Aldahunter Jan 04 '17 at 14:58
  • 1
    @AldaHunter see edit above. I was using `` instead of `{foo}` for optional package names. The error you received was LaTex's version of "file not found" – Jim Parker Jan 04 '17 at 21:11
  • thank you for the help, but fortunately I noticed that and it appears to work better, however now the python kernel I use crashes (see question edit above). I also found somewhere online to use the code: `matplotlib.rc('text', usetex = True) params = {'text.latex.preamble' : [r'\usepackage{amsmath}', r'\usepackage{amssymb}']} pyplot.rcParams.update(params)` I believe it does the same as your code, and I just swapped this for your edited code and unfortunately it still crashes the python kernel. However this time it doesn't appear to leave an error log. – Aldahunter Jan 04 '17 at 21:31
  • 1
    @AldaHunter I tried to run your code and had 2 errors. One involved the keyword `pivot` in line 19. This is a bug in earlier versions of `matplotlib` [https://github.com/matplotlib/matplotlib/issues/3907/]. I removed it, and the other error manifested which is that no font was found for the dotless j you attempt to label your axis with. Changed 'j' to 'l' and the plot worked for me. Not sure how to fix the label issue since i,l, k is not a normal labeling scheme. – Jim Parker Jan 04 '17 at 22:09
  • 1
    If you can live with non-bold face labels, the LaTeX string `r'$\mathbf{\hat{j}}$'` works for me. – Jim Parker Jan 04 '17 at 22:33
  • thank you so much for all your help, I've changed the code to remove the errors you've found. After all the hours I have spent on this I can definitely live with non-bold face labels! Unfortunately the `python kernel` still crashes! I figure if you can run the program it must be a problem with my software! If this helps I run the `Canopy Editor, Version 1.7.4.3348 (64 bit)` and for `LaTeX` I use `Texmaker 4.5`. I also saw online here: [link](http://matplotlib.org/users/usetex.html)... – Aldahunter Jan 06 '17 at 15:07
  • ...that i must install `Ghostscript` so I followed the link and installed the Postscript and PDF interpreter/renderer `Ghostscript 9.2`. I also belive I have `dvipng` installed as I use the `PdfLaTeX` option in `Texmaker`. As you can probably tell I know very little about these programs, so sorry and thank you for the help in advance. – Aldahunter Jan 06 '17 at 15:10
  • Also the link to Ghostscript that I installed is here: https://ghostscript.com/download/ – Aldahunter Jan 06 '17 at 15:11
  • **Edit** I also have `MiKTeX`, so I believe I already have `dvipng`, but not too sure, sorry – Aldahunter Jan 06 '17 at 15:30
  • First, just to backup a bit. Does the figure look like you want, except the labels? i.e., is matplotlib making the plot you want? – Jim Parker Jan 06 '17 at 20:09
  • Next, when kernel crashes what errors does it list? Since the code works for me, I'll need to see your errors. I'm not familiar with Canopy, but it must keep an error log somewhere. If not, try saving your script as foo.py. Then from command line run `python foo.py` and look at output errors. – Jim Parker Jan 06 '17 at 20:13
  • Yes the figure is exactly what I would like just with the hats over the dots. Unfortunately neither kernel nor command prompt list any errors, they just pop up a window with the message `python.exe has stopped working`. This is the image produced without using LaTeX: – Aldahunter Jan 07 '17 at 15:29
  • Also what I have noticed is that if I remove the `pyplot.savefig` command then the window pops up for the matplotib figure (however it is blank) and then the window to tell me `pythonw.exe has stopped working` comes up. So the code appears to be working up until the instance it tries to produce the image on screen (I think), which might be why it crashes before saving the image too. Sorry about the hassle and thank you for the help! – Aldahunter Jan 07 '17 at 15:33
  • 1
    Well, I'm not sure how to proceed now. `python` is stopping because I'll bet that `LaTeX` is missing another glyph, but without an error message/log, it's hard for me to troubleshoot. Do you know which version of `matplotlib` you are using? After importing, print `matplotlib.__version__` to show version string. If version < 1.4, you may have a known bug in font loading that is preventing you from using LaTeX fonts. – Jim Parker Jan 08 '17 at 02:49
  • Is there anyway I can stop `LaTeX` from missing the glyph - like install it somehow? There may be a message/log if it's written to another file after `command prompt`, but if it is unfortunately I wouldn't know where to find it. And after running the code you have said, I appear to have `matplotlib 1.5.1`. So it shouldn't be a bug should it? Again sorry about the hassle and I'm very grateful for you help – Aldahunter Jan 08 '17 at 17:41
  • 1
    No. Your version is good. Try adding the verbosity output I just added to answer above. You should be able to read the created file, and get some log information. Then we can move forward – Jim Parker Jan 08 '17 at 19:19
  • Well that's good that we know it's not that. I have added the debugging code, but unfortunately the file `foo-file.txt` which I've opened in Notepad is blank. Maybe I've added it in the wrong place, I have tried with the three lines inserted directly after my `pyplot.rcParams.update(params)`command (line 6) and then tried again with them directly before the `pyplot.savefig` command (line 42), on both the Canopy Editor and command line. Unfortunately all to no avail, with an empty text file. I have re-edited my code to show you where I have added the lines. – Aldahunter Jan 08 '17 at 21:14
  • 1
    I'm sorry, but I don't understand why we can't get any debug info. Without it, I'm stumped. You can try deleting the lines for `foo-file.txt`, and `.fileo`. This will cause the output to go to `stdout` by default, but if nothing was generated previously, I have little hope. Wait for someone more knowledgeable to speak up. – Jim Parker Jan 09 '17 at 21:00
  • Amazingly the code worked by removing the lines you said, and the`python kernel ` spits out what I'm assuming is the debug info (which I have now added to the question above). I hope this is what we need to figure out the problem. And thank you so much for all your help. – Aldahunter Jan 10 '17 at 17:49
  • just ran the code in the command prompt and it gave more lines out after the `kernel` did so have now copied them into the question above! Thanks. – Aldahunter Jan 10 '17 at 19:31
  • 1
    Ok, it appears you have a missing/corrupted font file, which is the source of the "missing glylph" errors. The solution is here [http://www.linux.cz/pipermail/texlive/2011-March/000105.html] for a Linux/TeXlive system. I'm not familiar with Windows/MikTeX setup, but presumably you can reload your font files to fix the errors as described. – Jim Parker Jan 10 '17 at 22:48
  • Thank you so much for all the help! Glad to have found the problem, just need to figure out how to solve it now! Also you link doesn't appear to work for me! – Aldahunter Jan 11 '17 at 13:15
  • Sorry, try www.linux.cz/pipermail/texlive/2011-March/000105.html. Must have done something wrong with the markup because it drops the http://www. and without it, the link won't work. – Jim Parker Jan 11 '17 at 20:35
  • Thank you! I had made another question on `TeX` community, asking about this [here](http://tex.stackexchange.com/questions/348150/installing-a-missing-corrupt-file-miktex?noredirect=1#comment854857_348150), when someone suggested using another font as `Helvetica` isn't a good maths font. By doing this has stopped the error, although `python.exe` still stops working and needs to be closed down before the code is complete. I have re-changed the debug error on the above question, as I don't understand what it means. Hopefully you can help, thank you! – Aldahunter Jan 11 '17 at 20:49
  • Just in case it helps I'm now using the `serif` family-font and the `Computer Modern` font. I'll quickly update my code now to show this. Thank you for all the help. – Aldahunter Jan 11 '17 at 20:55
  • 1
    @AldaHunter, I'm sorry but I don't know how to advise you anymore. The debug info does not list any errors that I can see. The last line states that dvipng is attempting to create a .png file and the log can be found at `C:\Users\alexd\.matplotlib\tex.cache\da3e0f170d11553ae39831280c346c0f.output`. Try looking at that for additional info. – Jim Parker Jan 13 '17 at 23:13
  • That's no problem, the bug is fiddly! Thank you for all your help! – Aldahunter Jan 19 '17 at 13:10
  • This solution worked rather than setting `mpl.rcParams.update({'text.latex.preamble': r"""Some multi-line preamble"""})` which was giving dvi errors such as https://stackoverflow.com/questions/31214214/matplotlib-error-latex-was-not-able-to-process-the-following-string-lp. Sadly I've no idea why. – oliversm Oct 15 '22 at 19:04
-1

If the answer of @Jim Parker didn't work with you - like what happened when I had the same problem - I think this will work correctly, as the above method changes the standard preamble, but this method adds the packages that you want to the preamble.

Code

plt.rcParams["text.latex.preamble"].join([
        r"\usepackage{dashbox}",              
        r"\setmainfont{xcolor}",
])
ouflak
  • 2,458
  • 10
  • 44
  • 49
  • Actually, this adds nothing to the preamble that pyplot uses. It just creates a new string and does nothing with it. You still need to call `plt.rc(...)` with the new string to actually set it. Also, it will break with more than two items because it will insert the old preamble between every pair of items in the list you specify. – Fritz Apr 14 '22 at 18:43