matplotlib标题内联字符串中符号上方的单词

2024-05-28 20:34:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的matplotlib图中创建一个信息性标题。我将这些信息添加到一个字符串中,这个字符串用于设置我的绘图标题。这个“标题”可能看起来像:

A  -->   B   -->   C   -->   D

现在,根据各种因素,我想在箭头上方加一个小字,表示一些东西,例如:

   walk      bus      train
A  -->   B   -->   C   -->   D

首先,我尝试使用LaTeX和\overset,但到目前为止,它似乎在matplotlib更新到3.4或其他版本之前不起作用。理论上,我也可以计算字符,然后在上面加一行字,然后把字几乎放在正确的位置,但我认为这不会很漂亮

那么有没有其他方法来实现这一点呢


Tags: 字符串版本信息绘图标题matplotlibtrain箭头
2条回答

你能用\stackrel吗?它与我的系统上的Matplotlib 3.1.3配合使用:

plt.title(r'$A\stackrel{\mathrm{walk}}{\longrightarrow}B$')
plt.show()

更新:对于Matplotlib 3.3:

plt.title(r'$A\genfrac{}{}{0}{}{\mathrm{walk}}{\longrightarrow}B$')

输出:

enter image description here

你也可以这样做

import matplotlib.pyplot as plt
import numpy as np

plt.rc('text', usetex=True)
params = {'text.latex.preamble' : [r'\usepackage{mathtools}', r'\usepackage{amsmath}', r'\usepackage{aligned-overset}']}
plt.rcParams.update(params)


# using some dummy data for this example
xs = np.random.randint( 0, 10, size=10)
ys = np.random.randint(-5, 5,  size=10)

# plot the points
fig = plt.figure(figsize=(10,6))
plt.title(r'$\mathbf{A  \buildrel{walk}\over{ >} B   \buildrel{bus}\over{ >}   C   \buildrel{train}\over{ >}   D}$', fontsize=16, fontweight='bold')
plt.subplot(111)
plt.plot(xs,ys,'b-')
plt.tick_params(axis='both', which='major', labelsize=20)
plt.tick_params(axis='both', which='minor', labelsize=20)
plt.grid()

LatesTitleImage

相关问题 更多 >

    热门问题