gpt4 book ai didi

matplotlib - 如何获取 Python 脚本文件名作为从 Jupyter 正确显示的绘图的标题?

转载 作者:行者123 更新时间:2023-12-01 03:30:27 24 4
gpt4 key购买 nike

我喜欢使用 python 脚本生成图形。该图应该将脚本文件名(带完整路径)作为标题的一部分。例如:

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['text.usetex'] = True

x = np.linspace(0, 10, 10)
titleString = __file__.replace('_', '\_')

plt.plot(x, x)
plt.title(titleString)
plt.show()

Spyder 中的 IPython 控制台正确显示标题:

enter image description here

但是,如果我从 Jupyter Notebook 中通过
%matplotlib inline
%run 'H:/Python/Playground/a_test'

我得到以下结果:

enter image description here

请注意,脚本路径和文件名不正确。有没有办法来解决这个问题?

最佳答案

我没有要检查的 Windows 机器,但是这个小弯路要转义所有 LaTeX 特殊字符 https://stackoverflow.com/a/25875504/6018688可能工作。还要注意 rcParams['text.usetex'] 的使用和 rcParams['text.latex.unicode'] .

import numpy as np
import matplotlib.pyplot as plt

import re

def tex_escape(text):
"""
:param text: a plain text message
:return: the message escaped to appear correctly in LaTeX
"""
conv = {
'&': r'\&',
'%': r'\%',
'$': r'\$',
'#': r'\#',
'_': r'\_',
'{': r'\{',
'}': r'\}',
'~': r'\textasciitilde{}',
'^': r'\^{}',
'\\': r'\textbackslash{}',
'<': r'\textless',
'>': r'\textgreater',
}
regex = re.compile('|'.join(re.escape(str(key)) for key in sorted(conv.keys(), key = lambda item: - len(item))))
return regex.sub(lambda match: conv[match.group()], text)


import matplotlib.pyplot as plt

plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.unicode'] = True

x = np.linspace(0, 10, 10)
titleString = tex_escape(__file__)

plt.plot(x, x)
plt.title(titleString)
plt.show()

关于matplotlib - 如何获取 Python 脚本文件名作为从 Jupyter 正确显示的绘图的标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38226867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com