如何在 matplotlib 中制作无衬线上标或下标文本?

Posted

技术标签:

【中文标题】如何在 matplotlib 中制作无衬线上标或下标文本?【英文标题】:How do I make sans serif superscript or subscript text in matplotlib? 【发布时间】:2015-02-26 04:48:51 【问题描述】:

我想在 matplotlib 图中的轴标签中使用下标。使用 LaTeX,我会将其设置为 $N_i$,这给了我斜体衬线字体。我知道我可以使用\mathrm 获得非斜体数学字体。但我想获取默认 matplotlib sans-serif 字体中的文本,以便它与图中的其余文本匹配。有没有不使用乳胶的下标文本的方法?

【问题讨论】:

【参考方案1】:

https://matplotlib.org/tutorials/text/mathtext.html

plt.figure()
plt.plot(x, y,'blue',label='$f(x)=e^-x$')
plt.plot(x,Mn3(x),'green',label='$M_3$')
plt.plot(x,Mn5(x),'red',label='$M_5$')
plt.plot(x,Mn7(x),'yellow',label='$M_7$')
plt.plot(x,Mn9(x),'pink',label='$M_9$')
plt.plot(x,Mn11(x),'black',label='$M_11$')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.legend()
plt.show()

enter image description here

【讨论】:

欢迎来到 SO!请注意,您刚刚回答了一个老问题。如果相关软件版本有任何更改导致已接受答案的语法被弃用,我们通常会回答此类问题。【参考方案2】:

您可以通过自定义rcParams 来实现。如果您有多个元素要自定义,您可以将它们存储为 dict 并更新 `rcParams':

params = 'mathtext.default': 'regular'           
plt.rcParams.update(params)

如果你想做一个单一的修改,你可以简单地输入:

plt.rcParams.update('mathtext.default':  'regular' )

在这方面,一个简单的例子如下:

import numpy as np
from matplotlib import pyplot as plt

x = np.linspace(1, 10, 40)
y = x**2

fig = plt.figure()
ax = fig.add_subplot(111)
params = 'mathtext.default': 'regular'           
plt.rcParams.update(params)
ax.set_xlabel('$x_my text$')
ax.set_ylabel('$y_i$')
ax.plot(x, y)
ax.grid()
plt.show()

您可以在matplotlib documentation 中找到有关RcParams 的更多信息。

【讨论】:

【参考方案3】:

使用\mathregular 来使用用于mathtext 之外的常规文本的字体:

$\mathregularN_i$

查看here 了解更多信息。

【讨论】:

以上是关于如何在 matplotlib 中制作无衬线上标或下标文本?的主要内容,如果未能解决你的问题,请参考以下文章

Linux Firefox 默认无衬线字体

即使 Arial 可用,浏览器仍在使用无衬线字体

自言自语--英文无衬线体和有衬线体

与 matplotlib 子图不一致的刻度标签字体

UI库materialize.css的font-family设置解释

如何使 QWebView/QWebPage 默认为衬线字体?