Matplotlib PGF images in subdirectory

For a more general workaround, in the case where you have multiple figure subfolders, you can define a new command which includes a localized redefinition:

\newcommand\inputpgf[2]{{
\let\pgfimageWithoutPath\pgfimage
\renewcommand{\pgfimage}[2][]{\pgfimageWithoutPath[##1]{#1/##2}}
\input{#1/#2}
}}

You then simply use it like so:

\inputpgf{path/to/figures}{figure.pgf}

The first argument specifies the local folder from which all image files for that figure will be included, and the second argument is just the filename of the PGF file.

Like the previous answer, this redefines the \pgfimage command, but only for the execution of the input command.


Quick answer

Since the command that imports the png files inside the pgf image is pgfimage, I redefined it like this:

\let\pgfimageWithoutPath\pgfimage 
\renewcommand{\pgfimage}[2][]{\pgfimageWithoutPath[#1]{figures/#2}}

The first line copies the original pgfimage command to a temporary pgfimageWithoutPath. The second line redefines pgfimage to be the same as pgfimage, but prefixing the path with figures/.

Read below for more details

I actually use the chapterfolder package, which allows me to split the document into subfolders, one per chapter. It's very cool for long documents but needs a workaround for importing the figures, exactly the same problem that you had. So in the end my importing for pgfs works like this:

  1. This is the same as above, but using chapterfolders' directives.

    \let\pgfimageWithoutCF\pgfimage
    \renewcommand{\pgfimage}[2][]{\pgfimageWithoutCF[#1]{\cfcurrentfolder\subfigurepath#2}}
    
  2. This is a wrapper to \input{figure.pgf}, which includes the chapter path:

    \newcommand{\includepgf}[1]{\input{\cfcurrentfolder\subfigurepath#1.pgf}}
    
  3. And finally this is a shortcut to make the figure fit exactly the width of the text (to be used like

    % usage: \resizepgf[<optional size (defaults to textwidth)>]{<filename>}
    \newcommand{\resizepgf}[2][\textwidth]{
        \resizebox{#1}{!}{\includepgf{#2}}
    }
    

Thanks to jevopi's little blog for the how-to.