0

I am new to python/coding and apologize if my question is too basic to have an answer available online as i am having a hard time finding the solution to my problem. I want to append multiple BytesIO() objects together and later write them as a single pdf file. Below is the code that i have managed so far. The tmp3 object bytes are equal to sum of tmp and tmp2 objects, however when i write tmp3 to disk, i get a single page pdf file with only the tmp2 figure. Please let me how can i manage to get a pdf with both the figures and on separate pages. Any suggestions involving a totally different approach are also welcomed.

cols = data.columns.values
col = cols.tolist()
g = sns.PairGrid(data[col])
g.map_diag(sns.histplot) #, hue=data['tar'], color='.9'
g.map_upper(sns.scatterplot) #, hue=data['tar']
g.map_lower(sns.kdeplot,cmap="Set2")

tmp = BytesIO()       
plt.savefig(tmp, format='pdf')
t=tmp.tell()
tmp.seek(0)

tmp2 = BytesIO()
fig, ax = plt.subplots(figsize=(20,15))
sns.heatmap(data.corr(),cmap='coolwarm', annot=True, fmt=".1f", ax=ax)
plt.savefig(tmp2,format='pdf')
p=tmp2.tell()
tmp2.seek(0)

tmp3 = BytesIO()
s = tmp3.tell()
tmp3.write(tmp.getvalue())
tmp3.write(tmp2.getvalue())
ss = tmp3.tell()
tmp3.seek(0)

temporarylocation="pairgrid.pdf"
with open(temporarylocation,'wb') as out:
    out.write(tmp3.read())
Ali Mehdi
  • 11
  • 1
  • Duplicate of https://stackoverflow.com/questions/21364405/saving-plots-to-pdf-files-using-matplotlib ? – Jody Klymak Aug 09 '21 at 15:04
  • No, i want to generate the plots in memory using BytesIO() and then combine those bytes of plots and write them as a single file in pdf. Saving the plots in memory using BytesIO() is crucial for the application. Thankyou – Ali Mehdi Aug 09 '21 at 18:40
  • You can open your PDfPages document as a BytesIO – Jody Klymak Aug 09 '21 at 19:26
  • Yes i am doing that in tmp and tmp2, but how do i combine those bytes and write them in a single pdf file. That is my question. – Ali Mehdi Aug 10 '21 at 10:14
  • You cannot concatenate PDF files just using the raw files. You need to assemble them, as PDfPages does. What you are doing is the command line equivalent of cat first.pdf second.pdf > result.pdf. And that will not create a valid pdf. – Jody Klymak Aug 10 '21 at 14:30
  • here is how i was able to do this. I also a small blog about this. https://medium.com/@SyedAliMehdiNaqvi?source=topics_v2---------1-84--------------------f53430ad_960f_436e_b4f4_e930e7f2db37-------19 – Ali Mehdi Oct 09 '21 at 14:16

0 Answers0