Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib, Consistent font using latex

Tags:

matplotlib

My problem is I'd like to use Latex titles in some plots, and no latex in others. Right now, matplotlib has two different default fonts for Latex titles and non-Latex titles and I'd like the two to be consistent. Is there an RC setting I have to change that will allow this automatically?

I generate a plot with the following code:

import numpy as np from matplotlib import pyplot as plt  tmpData = np.random.random( 300 )  ##Create a plot with a tex title ax = plt.subplot(211) plt.plot(np.arange(300), tmpData) plt.title(r'$W_y(\tau, j=3)$') plt.setp(ax.get_xticklabels(), visible = False)  ##Create another plot without a tex title plt.subplot(212) plt.plot(np.arange(300), tmpData ) plt.title(r'Some random numbers') plt.show() 

Here is the inconsistency I am talking about. The axis tick labels are thin looking relative to the titles.:

like image 427
ncRubert Avatar asked Jul 06 '12 18:07

ncRubert


1 Answers

To make the tex-style/mathtext text look like the regular text, you need to set the mathtext font to Bitstream Vera Sans,

import matplotlib matplotlib.rcParams['mathtext.fontset'] = 'custom' matplotlib.rcParams['mathtext.rm'] = 'Bitstream Vera Sans' matplotlib.rcParams['mathtext.it'] = 'Bitstream Vera Sans:italic' matplotlib.rcParams['mathtext.bf'] = 'Bitstream Vera Sans:bold' matplotlib.pyplot.title(r'ABC123 vs $\mathrm{ABC123}^{123}$') 

If you want the regular text to look like the mathtext text, you can change everything to Stix. This will affect labels, titles, ticks, etc.

import matplotlib matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.family'] = 'STIXGeneral' matplotlib.pyplot.title(r'ABC123 vs $\mathrm{ABC123}^{123}$') 

Basic idea is that you need to set both the regular and mathtext fonts to be the same, and the method of doing so is a bit obscure. You can see a list of the custom fonts,

sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist]) 

As others mentioned, you can also have Latex render everything for you with one font by setting text.usetex in the rcParams, but that's slow and not entirely necessary.

like image 77
lindyblackburn Avatar answered Oct 04 '22 04:10

lindyblackburn