如何获得 python 脚本文件名作为从 Jupyter 正确显示的绘图的标题?
How do I get a python script filename as title for a plot correctly shown from Jupyter?
我喜欢用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 控制台正确显示标题:
但是,如果我通过
从 Jupyter Notebook 中 运行 脚本(在 Windows 7 上,将 Anaconda 与 Jupyter Notebook 4.2.1 和 Spyder 2.3.9 一起使用)
%matplotlib inline
%run 'H:/Python/Playground/a_test'
我得到以下结果:
请注意,脚本路径和文件名不正确。有办法解决这个问题吗?
我没有 Windows 机器可以检查,但是这个转义所有 LaTeX 特殊字符 的小弯路可能会奏效。还要注意 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()
我喜欢用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 控制台正确显示标题:
但是,如果我通过
从 Jupyter Notebook 中 运行 脚本(在 Windows 7 上,将 Anaconda 与 Jupyter Notebook 4.2.1 和 Spyder 2.3.9 一起使用)%matplotlib inline
%run 'H:/Python/Playground/a_test'
我得到以下结果:
请注意,脚本路径和文件名不正确。有办法解决这个问题吗?
我没有 Windows 机器可以检查,但是这个转义所有 LaTeX 特殊字符 的小弯路可能会奏效。还要注意 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()