Python 保管Matplotlib地块

Python 保管Matplotlib地块,python,matplotlib,plot,latex,Python,Matplotlib,Plot,Latex,我正在尝试实施matplotlib图的保管程序,以便使用乳胶作品。有关更多参考信息,请查看以下链接: 下面的代码显示了我的尝试。我实现了以下代码: import matplotlib.pyplot as plt import numpy as np import pandas as pd import matplotlib from math import sqrt SPINE_COLOR = 'gray' def latexify(fig_width=None, fig_height=No

我正在尝试实施matplotlib图的保管程序,以便使用乳胶作品。有关更多参考信息,请查看以下链接:

下面的代码显示了我的尝试。我实现了以下代码:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib

from math import sqrt
SPINE_COLOR = 'gray'

def latexify(fig_width=None, fig_height=None, columns=1):
    """Set up matplotlib's RC params for LaTeX plotting.
    Call this before plotting a figure.

    Parameters
    ----------
    fig_width : float, optional, inches
    fig_height : float,  optional, inches
    columns : {1, 2}
    """

    # code adapted from http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples

    # Width and max height in inches for IEEE journals taken from
    # computer.org/cms/Computer.org/Journal%20templates/transactions_art_guide.pdf

    assert(columns in [1,2])

    if fig_width is None:
        fig_width = 3.39 if columns==1 else 6.9 # width in inches

    if fig_height is None:
        golden_mean = (sqrt(5)-1.0)/2.0    # Aesthetic ratio
        fig_height = fig_width*golden_mean # height in inches

    MAX_HEIGHT_INCHES = 8.0
    if fig_height > MAX_HEIGHT_INCHES:
        print("WARNING: fig_height too large:" + fig_height +
              "so will reduce to" + MAX_HEIGHT_INCHES + "inches.")
        fig_height = MAX_HEIGHT_INCHES

    params = {'backend': 'ps',
              'text.latex.preamble':['\usepackage{gensymb}'],
              'axes.labelsize': 8, # fontsize for x and y labels (was 10)
              'axes.titlesize': 8,
              'text.fontsize': 8, # was 10
              'legend.fontsize': 8, # was 10
              'xtick.labelsize': 8,
              'ytick.labelsize': 8,
              'text.usetex': True,
              'figure.figsize': [fig_width,fig_height],
              'font.family': 'serif'
    }

    matplotlib.rcParams.update(params)


def latexify(fig_width=None, fig_height=None, columns=1):
    """Set up matplotlib's RC params for LaTeX plotting.
    Call this before plotting a figure.

    Parameters
    ----------
    fig_width : float, optional, inches
    fig_height : float,  optional, inches
    columns : {1, 2}
    """

    # code adapted from http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples

    # Width and max height in inches for IEEE journals taken from
    # computer.org/cms/Computer.org/Journal%20templates/transactions_art_guide.pdf

    assert(columns in [1,2])

    if fig_width is None:
        fig_width = 3.39 if columns==1 else 6.9 # width in inches

    if fig_height is None:
        golden_mean = (sqrt(5)-1.0)/2.0    # Aesthetic ratio
        fig_height = fig_width*golden_mean # height in inches

    MAX_HEIGHT_INCHES = 8.0
    if fig_height > MAX_HEIGHT_INCHES:
        print("WARNING: fig_height too large:" + fig_height +
              "so will reduce to" + MAX_HEIGHT_INCHES + "inches.")
        fig_height = MAX_HEIGHT_INCHES

    params = {'backend': 'ps',
              'text.latex.preamble': ['\usepackage{gensymb}'],
              'axes.labelsize': 8, # fontsize for x and y labels (was 10)
              'axes.titlesize': 8,
              'text.fontsize': 8, # was 10
              'legend.fontsize': 8, # was 10
              'xtick.labelsize': 8,
              'ytick.labelsize': 8,
              'text.usetex': True,
              'figure.figsize': [fig_width,fig_height],
              'font.family': 'serif'
    }

    matplotlib.rcParams.update(params)


def format_axes(ax):

    for spine in ['top', 'right']:
        ax.spines[spine].set_visible(False)

    for spine in ['left', 'bottom']:
        ax.spines[spine].set_color(SPINE_COLOR)
        ax.spines[spine].set_linewidth(0.5)

    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    for axis in [ax.xaxis, ax.yaxis]:
        axis.set_tick_params(direction='out', color=SPINE_COLOR)

    return ax

df = pd.DataFrame(np.random.randn(10,2))
df.columns = ['Column 1', 'Column 2']



ax = df.plot()
ax.set_xlabel("X label")
ax.set_ylabel("Y label")
ax.set_title("Title")
plt.tight_layout()
plt.savefig("C:\Users\Laptop\Desktop\image1.pdf")


latexify()

ax = df.plot()
ax.set_xlabel("X label")
ax.set_ylabel("Y label")
ax.set_title("Title")
plt.tight_layout()
format_axes(ax)
plt.savefig("C:\Users\Laptop\Desktop\image2.pdf")
我获得以下语法错误并完成回溯:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2018.3.3\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2018.3.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Laptop/PycharmProjects/PythonThesisVU/PLOTS.py", line 41
    'text.latex.preamble':['\usepackage{gensymb}'],
                          ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape

所需的avant字体如下所示:

此行出现错误:

          'text.latex.preamble':['\usepackage{gensymb}'],
Python将
'\usepackage{gensymb}'
中的
\u
解释为。您可以通过使用
\\
转义
\\
或使用原始字符串来修复此问题

例如:

          'text.latex.preamble':[r'\usepackage{gensymb}'],
或:


将更正错误。

此行出现错误:

          'text.latex.preamble':['\usepackage{gensymb}'],
Python将
'\usepackage{gensymb}'
中的
\u
解释为。您可以通过使用
\\
转义
\\
或使用原始字符串来修复此问题

例如:

          'text.latex.preamble':[r'\usepackage{gensymb}'],
或:


将更正错误。

文本。fontsize
不是有效参数。而是
font.size
。还必须转义反斜杠或使用原始字符串
r'\usepackage{gensymb}'
text.fontsize
不是有效的参数。而是
font.size
。还必须转义反斜杠或使用原始字符串
r'\usepackage{gensymb}'

请发布完整的回溯,这将告诉读者您的代码中发生错误的确切位置。感谢您富有洞察力的评论。我刚刚添加了完整的回溯。请发布完整的回溯,这将告诉读者您的代码中发生错误的确切位置。感谢您有见地的评论。我刚刚添加了完整的回溯。谢谢你的解释。这确实是个错误。我将你的评论标记为答案。Craig,你知道如何将font.family调整为avant,使其与文本格式完美匹配吗。这需要加载\usepackage{avant}。所以我尝试了以下方法(请参见编辑1)。我不熟悉latex字体。请提出有关将字体设置为avant的新问题。感谢您的解释。这确实是个错误。我将你的评论标记为答案。Craig,你知道如何将font.family调整为avant,使其与文本格式完美匹配吗。这需要加载\usepackage{avant}。所以我尝试了以下方法(请参见编辑1)。我不熟悉latex字体。请提出一个关于将字体设置为avant的新问题。谢谢您的快速回复,您是对的。幸运的是,Python非常明确地告诉我text.fontsize不正确。谢谢如果您知道如何使字体系列与“编辑1”中给出的avant兼容,我们将不胜感激。谢谢您的快速回复,您是对的。幸运的是,Python非常明确地告诉我text.fontsize不正确。谢谢如果您知道如何使字体系列与编辑1中给出的avant兼容,将不胜感激。