I have recently (i.e., yesterday) discovered matplotlib as a much better alternative to Matlab for plots. Unfortunately, my knowledge of python is close to zero.
I would like to use \mathbb{} in the legend and/or axes (for example, to denote expected value or variance) and it seems that this requires the additional STIX fonts (see, e.g., here and here). However, I haven't been able to include these fonts in my code so far.
In the following example, I would like to replace \mathrm{E} --> \mathbb{E} and \mathrm{V} --> \mathbb{V}. Is there a simple way to do it?
import numpy as np
import scipy.io
from matplotlib import pyplot as plt
plt.figure(figsize=[3.3, 3.3])
plt.rcParams.update({'font.size': 8, 'text.usetex': True})
plt.plot([1,2,3,4], [1,2,3,4], label=r'$\mathrm{E}[x]$')
plt.plot([1,2,3,4], [1,4,9,16], label=r'$\mathrm{V}[x]$')
plt.grid()
plt.xlabel('x')
plt.legend(loc='upper left')
plt.savefig('filename.pdf', format='pdf')
plt.show()
\mathbb is provided by the LaTeX package amsfonts, so you have to load this package for the figure to compile properly. You can load packages using the text.latex.preamble setting, as follows:
import numpy as np
import scipy.io
from matplotlib import pyplot as plt
plt.figure(figsize=[3.3, 3.3])
plt.rcParams.update({
'font.size': 8,
'text.usetex': True,
'text.latex.preamble': r'\usepackage{amsfonts}'
})
plt.plot([1,2,3,4], [1,2,3,4], label=r'$\mathbb{E}[x]$')
plt.plot([1,2,3,4], [1,4,9,16], label=r'$\mathbb{V}[x]$')
plt.grid()
plt.xlabel('x')
plt.legend(loc='upper left')
plt.savefig('filename.pdf', format='pdf')
plt.show()

Alternatively, to use the STIX fonts you refer to in your question, you can use matplotlib's built in TeX parser, not using LaTeX at all for your text handling (test.usetex can be False). In this case, however, note that \mathbb{} produces italic text by default, and you need to combine it with \mathrm{} as \mathrm{\mathbb{}} to get upright text (as in the example you linked). A possible version of your code is then:
import numpy as np
import scipy.io
from matplotlib import pyplot as plt
plt.figure(figsize=[3.3, 3.3])
plt.rcParams.update({'font.size': 8})
plt.plot([1,2,3,4], [1,2,3,4], label=r'$\mathrm{\mathbb{E}}[x]$')
plt.plot([1,2,3,4], [1,4,9,16], label=r'$\mathrm{\mathbb{V}}[x]$')
plt.grid()
plt.xlabel('x')
plt.legend(loc='upper left')
plt.savefig('filename.pdf', format='pdf')
plt.show()
In this case, this is the result. (posted as a link to limit the height of this answer)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With