Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: Times New Roman appears bold

For some reason when using Times New Roman in my mpl plots it appears bold. Other fonts are OK.

Here is a minimal example, and the result (inside a Word document, for comparison with what I expect Times New Roman to look like).

import matplotlib as mpl
import matplotlib.pyplot as plt

with plt.style.context('word'):
  fig = plt.figure(1, figsize=(3.4, 2.1))
  ax1 = plt.subplot(111)
  ax1.plot([1,2,3,4,5], '+--')
  ax1.text(0.5, 3.5, r"Brown $\alpha + 12 \sum_ix$")
  ax1.text(0.5, 3, r"1.0 2.0")
  ax1.set_xlabel('normal 1.0 and math $1.0$')
  ax1.set_ylabel('Times New Roman')
  plt.tight_layout()
  fig.savefig('word.pdf')

with the word stylesheet containing

backend: PS
text.usetex: False
font.family: serif
font.serif: Times New Roman
font.size: 11
axes.titlesize: 11
axes.labelsize: 11

The plot is included in the document with its actual size (3.4'' by 2.1'').

The font is correctly found and it is also working in math-mode (see the alpha in the plot). It just seems that this is bold...

enter image description here

like image 919
Cedric H. Avatar asked Nov 27 '15 10:11

Cedric H.


3 Answers

As mentioned the font selection algorithm picks the first font in the Time New Roman family, which has four different files (bold, bold italic, italic and regular). So the steps would be:

  1. Go to C:\Windows\Fonts\Times New Roman
  2. Right-click → Sort by → Descending (the order will change so the Times New Roman Regular will end up as the first, and that will be the font the algorithm will choose).
like image 184
Pamy Avatar answered Oct 26 '22 14:10

Pamy


Digging into more details I realized that the bug is real and that mpl is actually selecting a Times New Roman Bold font.

The font selection algorithm in font_manger.py assigns weights on every font it finds based on the family, variant, weight, etc. (around line 1290). The "name" coming from Times New Roman Bold.ttf is just 'Times New Roman' which might make sense, but the weight is 500, the same value as the regular font:

<Font 'Times New Roman' (Times New Roman Bold.ttf) normal normal 500 normal> with score 0.1
<Font 'Times New Roman' (Times New Roman.ttf) normal normal 500 normal> with score 0.1

On my Mac and Linux setup the bold one is encountered first and is selected by the code

 if score < best_score:
     best_score = score
     best_font = font

I dirty patch is to replace < by <=...

like image 35
Cedric H. Avatar answered Oct 26 '22 14:10

Cedric H.


I know the question is very old, but it still is a problem, at least for me on my mac. I found a very easy solution to this problem, posted by azag0 on github

del matplotlib.font_manager.weight_dict['roman']
matplotlib.font_manager._rebuild()

https://github.com/matplotlib/matplotlib/issues/5574

like image 45
dennis Avatar answered Oct 26 '22 14:10

dennis