使用 matplotlib 以斜体书写标签时如何避免字体更改?

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

字体更改为:

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)

我按如下方式连接我的文本标签:

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

然而,Times new roman 在所有出现斜体的地方都消失了。它发生在 xtick_labels 的以下情节中,但发生在 ax.annotate()ax.legend()

我相信像你这样使用乳胶会导致字体回退到 mathfont。

您可以直接使用 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')