2016-07-06 44 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() 
相關問題