Matplotlib for $\LaTeX$

In [1]:
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt

import numpy as np

1. Unify fonts between Matplotlib and $\LaTeX$¶

We can use $\LaTeX$ for text rendering to unify the font across matplotlib figures and $\LaTeX$ documents. (tex executables are required)

Defaut text renderer and font:¶

In [2]:
fig, ax = plt.subplots(figsize=(3, 2))
fig.set_dpi(200)
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')
plt.show()

Text rendering with $\LaTeX$ and set the font to $\LaTeX$'s default font 'Computer Modern'¶

plt.rcParams.update({
    "text.usetex": True,
    "font.family": "Computer Modern"
})
In [3]:
plt.rcParams.update({
    "text.usetex": True,
    "font.family": "Computer Modern"
})
In [4]:
fig, ax = plt.subplots(figsize=(3, 2))
fig.set_dpi(200)
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')
plt.show()
In [ ]: