Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib greek symbols differ in show() and savefig()

I'm trying to get a simple greek letter mu to display in roman font in a saved figure with matplotlib. I have tried two methods:

  1. plt.xlabel(u'Wavelength (\u03bc m)')

This method works fine when I do a show(), but when I try to use savefig(), the mu character shows as a rectangle when saved as a .png. If I save as a .pdf, the symbol is missing entirely.

  1. plt.xlabel(r'Wavelength ($\mathrm{\mu}$m)')

This method renders a greek letter with both show() and savefig(), but the character is still in italics in each case, despite requesting a roman font.

What's the trick?

like image 541
Doug Avatar asked Nov 10 '22 00:11

Doug


1 Answers

I have very good experience with having all text (regular and math) beeing typeset by LaTeX. Just set your rc-settings accordingly before plotting:

import matplotlib.pyplot as plt

plt.rcParams['text.usetex'] = True #Let TeX do the typsetting
plt.rcParams['text.latex.preamble'] = [r'\usepackage{sansmath}',r'\sansmath']
#Force sans-serif math mode
plt.rcParams['font.family'] = 'sans-serif' # ... for regular text
plt.rcParams['font.sans-serif'] = 'Helvetica' # Choose a nice font here

You can then simply say:

plt.xlabel('Wavelength ($\mu$)')

Inspired by my own answer here: Type 1 fonts with log graphs

like image 195
wsj Avatar answered Nov 14 '22 22:11

wsj