jeroaranda
jeroaranda

Reputation: 61

How to avoid font change when writing a label in Italics with matplotlib?

The font is changed with:

import os
from matplotlib import font_manager as fm, rcParams
fpath = os.path.join(rcParams["datapath"], '/gdrive/My Drive/animal/data/times-new-roman.ttf')
prop = fm.FontProperties(fname=fpath,size=17)

I am concatenating my text labels as follows:

label = $\it{'+ text + '}$ from italic symbols in matplotlib?

However Times new roman disappears everywhere italics appear. It happens in the following plot with the xtick_labels, but has happened with ax.annotate() and ax.legend()

enter image description here

Upvotes: 0

Views: 347

Answers (1)

Paul H
Paul H

Reputation: 68126

I believe that using latex like you have is causing the font to fallback to the mathfont.

You can set the typeface and other font properties directly with latex:

## -------- figure setup
from matplotlib import pyplot
from matplotlib import ticker
x_vals = {0: 'This', 1: 'That', 2: 'The Other'}
y_vals = {0: 'They', 1: 'Them', 2: 'Everyone Else'}

fig, ax = pyplot.subplots()
ax.set_xlim(-0.5, 2.5)
ax.set_ylim(-0.5, 2.5)

ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: x_vals.get(x, '')))
ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: y_vals.get(x, '')))

ax.tick_params('x', labelrotation=45)

## ------ WHERE PROPERTIES GET SET
for t in ax.get_xticklabels():
    t.set_fontstyle('italic')
    
for t in ax.get_yticklabels():
    t.set_fontweight('heavy')

enter image description here

Upvotes: 1

Related Questions