smcs
smcs

Reputation: 2004

Setting a font from .otf file as standard in matplotlib

On Ubuntu 20.04 I downloaded a new font to /usr/share/fonts/opentype/Helvetica_Neue_LT_Pro/HelveticaNeueLTPro-Cn.otf.

The font shows up in the Ubuntu font manager:

helvetica list in Ubuntu font manager

I can use it in matplotlib like this:

import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3])

fpath = "/usr/share/fonts/opentype/Helvetica_Neue_LT_Pro/HelveticaNeueLTPro-Cn.otf"

prop = fm.FontProperties(fname=fpath)
ax.set_title("Helvetica Test", fontproperties=prop)

plt.show()

The result is:

the new font works

But this is annoying for my script with many figures. How can I set this font globally? This does not work:

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3])

plt.rcParams['font.family'] = "Helvetica Neue LT Pro, 57 Condensed"

ax.set_title("Helvetica Test")

plt.show()

There is no error or warning, but the result is:

enter image description here

Obviously the standard font is used here.

Edit: Thanks to tomjn I had a look at the fontlist at /home/nettef/.cache/matplotlib/fontlist-v330.json. The font is listed here as:

  {
    "fname": "/usr/share/fonts/opentype/Helvetica_Neue_LT_Pro/HelveticaNeueLTPro-Cn.otf",
    "name": "Helvetica Neue LT Pro",
    "style": "normal",
    "variant": "normal",
    "weight": 400,
    "stretch": "condensed",
    "size": "scalable",
    "__class__": "FontEntry"
  },

But there are 50 others with the field "name": "Helvetica Neue LT Pro". Could this be the central problem? I can actually manually change the name to "name": "Helvetica Neue LT Pro Condensed" and then set it globally like this:

plt.rcParams['font.sans-serif'] = "Helvetica Neue LT Pro Condensed"

This seems like a bad solution though since the fontlist is apparently auto generated and could break my script at any time.

Upvotes: 0

Views: 1275

Answers (1)

tomjn
tomjn

Reputation: 5389

Your json is very useful! I think you want

plt.rcParams["font.family"] = "sans-serif"
plt.rcParams["font.sans-serif"] = ["Helvetica Neue LT Pro"] + plt.rcParams["font.sans-serif"]
plt.rcParams["font.stretch"] = "condensed"  # This is probably the key setting!

You could put these in an rcfile too for convenience

Upvotes: 2

Related Questions