2017-01-09 14 views
1

私はpandasデータフレームのチャンクをループし、pdfにチャートを追加しようとしています。ここでのサンプルコードは、次のとおりです。searborn注釈が前に上書きされます

import random 
import pandas as pd 
import matplotlib.pyplot as plt 
import numpy as np 
import seaborn as sns 
from matplotlib.backends import backend_pdf 

df = pd.DataFrame({'a':[a + + random.random() for a in range(12)] , 
        'b':[ b + random.random() for b in range(12,24)]}) 
print(df) 

chunk_size = 3 # number of rows in heatmap 
n_chunks = len(df)//chunk_size # number of pages in heatmap pdf 

with backend_pdf.PdfPages('chart.pdf') as pdf_pages:  
    for e,(k,g) in enumerate(df.groupby(np.arange(len(df))//chunk_size)): 
     #print(k,g.shape) 
     snsplot = sns.heatmap(g, annot=True, cbar=False, linewidths=.5) #fmt="d",cmap="YlGnBu", 
     pdf_pages.savefig(snsplot.figure) 

このコードは大丈夫ページが追加されますが、前のページからすべての注釈が続くすべてのページにオーバーレイ(保存)しているようです。

enter image description here enter image description here enter image description here enter image description here enter image description here

答えて

3

同じAxesオブジェクトに起こっている、それはので、あなたのプロットのすべてをplt.gca()を使用しているあなたはsns.heatmapを呼び出すたびに(各ループは、すべてのように遅い、あまりにも取得される可能性があります以前のアーティストはレンダリングされていますが、最新のアーティストによって隠されています)。

私はseabornはどこ描画を知っていると明示的に各ループでそれをクリアしてAxesオブジェクトに渡し

fig, ax = plt.subplots() 
with backend_pdf.PdfPages('chart.pdf') as pdf_pages:  
    for e,(k,g) in enumerate(df.groupby(np.arange(len(df))//chunk_size)): 
     #print(k,g.shape) 
     ax.cla() 
     snsplot = sns.heatmap(g, annot=True, cbar=False, linewidths=.5, ax=ax) 
     pdf_pages.savefig(snsplot.figure) 

のようなものを示唆しています。

関連する問題