# Automatically externalizing content of a PGFplot as a PNG

I've got basically the same issue as in this question: I have a rather complicated plot made with PGFplots and I can get a very significant file size reduction by using a rasterized image (PNG) instead of a PDF. The main solution suggested in that question's answer is to convert the externalized PDF into high resolution PNG files and include those back in the document, presumably using \includegraphics or the equivalent. OK, fine, I can do that.

But let's say I'd like to keep the axes and descriptions in vector "format", and only have the content of the plot as a PNG. A lot of the technology to do this automatically already exists:

• PGFplots can create the content of an axis without the lines and labels (though still including titles and legends) using the hide axis style
• It can export single-plot images using the external library
• It can automatically rasterize externalized images using e.g. convert, as requested in this question
• It can use an external raster image as the content of a plot, using the \addplot graphics mechanism

So could we stitch together all these steps to make a PGFplots style that automatically writes out the content of a plot as a PNG file and then displays it inside axes? (My use case involves 2D plots only, though if someone wanted to take on the challenge of doing this for 3D plots I wouldn't complain!)

The main obstacle, for me at least, is externalizing a plot that is not directly displayed in the document, and doesn't actually exist as its own separate tikzpicture. Taking a sample plot:

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\end{axis}
\end{tikzpicture}
\end{document}


my thought would be to (somehow) convert the tikzpicture environment to

  \begin{tikzpicture}[undisplayed,tikz/external/figure name=randomname]
\begin{axis}[hide axis]
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}

and only display the second picture (hence the hypothetical undisplayed style, though I don't know if such a thing is really possible). Of course I'm not sure how to do this. Perhaps someone more familiar with the PGFplots/TikZ internals would know a way, if it's possible? Or perhaps there's some other way to get to the same end, maybe by choosing what styles to apply to the picture depending on what step in the process we're in.