{"record":{"id":"7c29750b7fe77e6e","repo":"matplotlib/matplotlib","slug":"streamed-pgf-code-does-not-support-raster-graphics","errorCode":null,"errorMessage":"streamed pgf-code does not support raster graphics, consider using the pgf-to-pdf option","messagePattern":"streamed pgf-code does not support raster graphics, consider using the pgf-to-pdf option","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"lib/matplotlib/backends/backend_pgf.py","lineNumber":649,"sourceCode":"        _writeln(self.fh, r\"\\pgfusepath{%s}\" % \",\".join(actions))\n\n    def option_scale_image(self):\n        # docstring inherited\n        return True\n\n    def option_image_nocomposite(self):\n        # docstring inherited\n        return not mpl.rcParams['image.composite_image']\n\n    def draw_image(self, gc, x, y, im, transform=None):\n        # docstring inherited\n\n        h, w = im.shape[:2]\n        if w == 0 or h == 0:\n            return\n\n        if not os.path.exists(getattr(self.fh, \"name\", \"\")):\n            raise ValueError(\n                \"streamed pgf-code does not support raster graphics, consider \"\n                \"using the pgf-to-pdf option\")\n\n        # save the images to png files\n        path = pathlib.Path(self.fh.name)\n        fname_img = \"%s-img%d.png\" % (path.stem, self.image_counter)\n        Image.fromarray(im[::-1]).save(path.parent / fname_img)\n        self.image_counter += 1\n\n        # reference the image in the pgf picture\n        _writeln(self.fh, r\"\\begin{pgfscope}\")\n        self._print_pgf_clip(gc)\n        f = 1. / self.dpi  # from display coords to inch\n        if transform is None:\n            _writeln(self.fh,\n                     r\"\\pgfsys@transformshift{%fin}{%fin}\" % (x * f, y * f))\n            w, h = w * f, h * f\n        else:","sourceCodeStart":631,"sourceCodeEnd":667,"githubUrl":"https://github.com/matplotlib/matplotlib/blob/b379c1b69e012b142c0f496a52bcb30513802d72/lib/matplotlib/backends/backend_pgf.py#L631-L667","documentation":"PGF output references raster images with \\includegraphics pointing at PNG files written next to the output file. That only works when the destination is a real file on disk (self.fh has a name attribute); printing pgf code into a stream such as io.BytesIO or sys.stdout cannot reference sibling files, so draw_image raises ValueError recommending the pgf-to-pdf route.","triggerScenarios":"fig.savefig(buf, format='pgf') with buf a BytesIO/StringIO while the figure contains an image artist (imshow, imread-based plots); any print_pzf call where the file handle has no usable name.","commonSituations":"Web services generating pgf bytes in memory; test suites capturing output in BytesIO; refactoring path-based savefig to stream-based without remembering the sibling-PNG constraint.","solutions":["Save to a real path instead: fig.savefig('out.pgf'), then read the file (and the sibling -img*.png files) from disk","Keep the pgf backend but request PDF: fig.savefig('out.pdf') — the pgf-to-pdf path works from temp files and supports raster images","For in-memory PDF with images, switch to the native pdf backend: fig.savefig(buf, format='pdf', backend='pdf')"],"exampleFix":"# before\nbuf = io.BytesIO()\nfig.savefig(buf, format='pgf')  # figure contains imshow -> ValueError\n\n# after\nfig.savefig('out.pgf')            # real path: sibling PNGs can be written\n# or: fig.savefig('out.pdf')       # pgf-to-pdf route","handlingStrategy":"validation","validationCode":"import os\n\ndef pgf_target_ok(target) -> bool:\n    return isinstance(target, (str, os.PathLike))\n\nif figure_has_images(fig) and not pgf_target_ok(dest):\n    dest = tempfile.mkdtemp() + '/out.pgf'  # write to disk instead\nfig.savefig(dest, format='pgf')","typeGuard":null,"tryCatchPattern":"try:\n    fig.savefig(buf, format='pgf')\nexcept ValueError as err:\n    if 'raster graphics' not in str(err):\n        raise\n    fig.savefig('out.pdf')  # pgf-to-pdf route supports images","preventionTips":["Never stream pgf output to BytesIO when the figure contains imshow or other images","Save pgf to a directory path so the -img*.png siblings can be written and shipped together","Use format='pdf' under the pgf backend when both in-memory bytes and images are required"],"tags":["matplotlib","pgf","file-like-object","raster-image","export"],"backgroundTag":"output-stream-unsupported","analyzedSha":"b379c1b69e012b142c0f496a52bcb30513802d72","analyzedAt":"2026-08-21T23:31:55.468Z","schemaVersion":2},"datasetVersion":"2026-08-22T04:17:13.399Z"}