Saving PDFs with the snippet
with outfile.open("wb") as f:
plt.savefig(f, dpi=300)
leads to corrupted PDFs. The code executes perfectly fine but the files cannot be opened (see below for error when trying to open the file with Preview on Mac OS 15.4.1).

Using the approach
plt.savefig(outfile, dpi=300)
leads to uncorrupted files.