4

I like to use a python script to generate a figure. That figure should have the script filename (with full path) as part of the title. For example:

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()

The IPython console in Spyder shows the title correctly:

enter image description here

However, if I run the script (on Windows 7, using Anaconda with Jupyter Notebook 4.2.1 and Spyder 2.3.9) from within a Jupyter Notebook via

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

I get the following result:

enter image description here

Note that the scripts path and filename is not correct. Is there a way to fix this?

DaPhil
  • 1,509
  • 4
  • 25
  • 47
  • When I run it as you do in the second example on a Mac OSX, title contains the whole file name including path. These commands produced the exact same output: `%run file` and `%run /path/file` – fabianegli Jul 06 '16 at 15:14
  • @fabianegli Ok. I should have mentioned that I am running this on a Windows machine. – DaPhil Jul 06 '16 at 15:16
  • I figured that out already the paths in the question, that's why i added my OS :-) – fabianegli Jul 06 '16 at 15:19
  • you might get more answers if you specify the exact OS as well as matplotlib and jupyter version of your setup. – fabianegli Jul 06 '16 at 18:59

1 Answers1

2

I have no Windows machine to check, but this little detour with escaping all LaTeX special characters https://stackoverflow.com/a/25875504/6018688 might work. Also note the use of rcParams['text.usetex'] and 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()
Community
  • 1
  • 1
fabianegli
  • 2,056
  • 1
  • 18
  • 35