Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: how to access internal cm font?

I am using python2.7 on Windows 10, with Anaconda, and having some issue configuring font.

First of all, I am aware that this issue is quickly resolved if I install required fonts. But I want to know whether I can resolve this WITHOUT installing any new font.

I have this simple code for plotting.

import matplotlib as mpl
mpl.rcParams['font.family']='serif'
mpl.rcParams['mathtext.fontset']='cm'
import matplotlib.pyplot as plt

plt.plot([1,2,3],[4,3,4])
plt.text(1.5,4,'Hello!')
plt.show()

and it works perfectly. Since Computer Modern font is not installed on my computer(bizarre considering I installed TeXLive, but that's irrelevant.), matplotlib must have it internally. Now, I want my serif font to be computer modern also. I thought adding

mpl.rcParams['font.serif']=['cm']

between mpl.rcParams[] lines would work. Instead, it gave this warning

C:\ProgramData\Anaconda2\lib\site-packages\matplotlib\font_manager.py:1297: UserWarning: findfont: Font family [u'serif'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))

This is quite confusing. I don't have computer modern font installed on my computer, but since setting mathtext.fontset as cm worked fine, I think there should be some way to allocate that internal font for font.serif.

What would be a solution for this?

like image 447
Hojin Cho Avatar asked Oct 20 '25 01:10

Hojin Cho


1 Answers

The correct ttf-file corresponding to the internal Computer Modern font used by mpl is stored somewhere in the data path. The following code should do the job:

import matplotlib as mpl
import matplotlib.font_manager as font_manager

mpl.rcParams['font.family']='serif'
cmfont = font_manager.FontProperties(fname=mpl.get_data_path() + '/fonts/ttf/cmr10.ttf')
mpl.rcParams['font.serif']=cmfont.get_name()
mpl.rcParams['mathtext.fontset']='cm'
mpl.rcParams['axes.unicode_minus']=False
import matplotlib.pyplot as plt

plt.plot([-1,2,3],[4,3,4])
plt.text(1.5,4,'Hello!')
plt.show()

The line

mpl.rcParams['axes.unicode_minus']=False

is required to solve some issue with the minus-sign.

like image 159
questioner Avatar answered Oct 21 '25 19:10

questioner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!