Saving figures creates blank pdfs

I have the following lines that show up fine in the ide but create big blank pdfs:

sc.pl.violin(adata_segerstolpe, ['n_genes_by_counts'], groupby='cellType')
plt.savefig(os.path.join(path, "genes_abdg.pdf"))
plt.show()

Is there a way to make this work?

Hey @mkarikom!

I would either just add save='_genes_abdg.pdf' to the sc.pl.violin() call to use the save= parameter, or I would add show=False to return the axis object to then just matplotlib calls to save the figure.

1 Like

Thanks @LuckyMD,
I think the following should be sufficient but I get this error:

path = "/home/au/code/DeconSC/data/Segerstolpe2016/figs/"
if not os.path.exists(path):
       os.makedirs(os.path.dirname(path))
rcParams['figure.figsize'] = 5,5
sc.pl.violin(adata_segerstolpe, ['n_genes_by_counts', 'total_counts'],jitter=0.4, multi_panel=True,save=os.path.join(path, 'genes_counts_violin.pdf'))

WARNING: saving figure to file figures/violin/home/au/code/DeconSC/data/Segerstolpe2016/figs/genes_counts_violin.pdf
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
~/code/DeconSC/data/step.02.import_music_data.py in 
----> 68 sc.pl.violin(adata_segerstolpe, ['n_genes_by_counts', 'total_counts'],jitter=0.4, multi_panel=True,save=os.path.join(path, 'genes_counts_violin.pdf'))

~/anaconda3/envs/pyro385/lib/python3.8/site-packages/scanpy/plotting/_anndata.py in violin(adata, keys, groupby, log, use_raw, stripplot, jitter, size, layer, scale, order, multi_panel, xlabel, ylabel, rotation, show, save, ax, **kwds)
    815                 ax.tick_params(axis='x', labelrotation=rotation)
    816     show = settings.autoshow if show is None else show
--> 817     _utils.savefig_or_show('violin', show=show, save=save)
    818     if not show:
    819         if multi_panel and groupby is None and len(ys) == 1:

~/anaconda3/envs/pyro385/lib/python3.8/site-packages/scanpy/plotting/_utils.py in savefig_or_show(writekey, show, dpi, ext, save)
    311     show = settings.autoshow if show is None else show
    312     if save:
--> 313         savefig(writekey, dpi=dpi, ext=ext)
    314     if show:
    315         pl.show()

Do sanity check:

os.path.exists(path)
True

Regarding the error, I’m just not sure where:

figures/violin/home/au/code/DeconSC/data/Segerstolpe2016/figs/genes_counts_violin.pdf

is coming from since I gave it an absolute path

Thanks, the show=False option works great with:

fig = sc.pl.violin(adata_segerstolpe, ['n_genes_by_counts', 'total_counts'],jitter=0.4, multi_panel=True,show=False)
fig.savefig(os.path.join(path, "genes_counts_violin.pdf"))

Glad it worked for you. The save parameter works by appending a string to the end of violin in this case and saves this in a “figures” folder in the current directory. So rather than using os.path.join(...) you just to input something like _mystring.pdf.

1 Like