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

标签 matplotlib plot spyder jupyter-notebook

我喜欢使用 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/

相关文章:

python - 如何在 Alpine 上安装 matplotlib

python - python 2.7中的FFMPEG文件编写器

R:如何标记绘图上的某些点

matlab - 如何更改 Matlab 图中线条的顺序?

python - seaborn (distplot) yaxis 可以自动重新缩放吗?

pip - 使用 pip 安装 PyODBC

python - Pandas:绘制从上到下的表现者

python - 在 pandas 中,将散点图添加到线图上

python-3.x - 为什么我得到 "IndentationError: expected an indented block"

python - 我无法让 ipython 控制台在spyder 中播放声音