2016-07-06 48 views
4

我喜欢使用python脚本来生成一个图形。该图应该具有脚本文件名(包含完整路径)作为标题的一部分。例如:如何从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的控制台显示标题正确:

enter image description here

但是,如果我运行脚本(在Windows 7上,使用蟒蛇与Jupyter笔记本4.2.1和通过

%matplotlib inline 
%run 'H:/Python/Playground/a_test' 

我得到以下结果Spyder的2.3.9)从Jupyter笔记本内:

enter image description here

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

+0

当我像Mac OSX上的第二个例子那样运行它时,标题包含整个文件名,包括路径。这些命令产生完全相同的输出:'%run file'和'%run/path/file' – fabianegli

+0

@fabianegli好的。我应该提到我正在Windows机器上运行它。 – DaPhil

+0

我想这已经是问题中的路径,这就是为什么我添加了我的操作系统:-) – fabianegli

回答

2

我没有Windows机器可以检查,但是这个小小的绕道转移所有乳胶特殊字符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() 
相关问题