Skip to content Skip to sidebar Skip to footer

Trouble With Saving Grouped Seaborn Facetgrid Heatmap Data Into A Directory

I've been struggling to save my graphs to the specific directory with some certaion look. Here is the example data and what I've tried so far import pandas as pd import numpy as n

Solution 1:

The problems comes from the fact that you are trying to loop through the two ltt levels, but then you don't filter your database on those levels.

for l in data.ltt.unique():
    g = sns.FacetGrid(data[data.ltt==l], ....)

Also, you have a conflict with the variable l that's used once for the ltt level and the second time in the loop for the row labels. Try using more descriptive variable names in your code.

Here is the full working code:

import pandas as pd
import numpy as np
import itertools
import seaborn as sns
from matplotlib.colors import ListedColormap

print("seaborn version {}".format(sns.__version__))
# R expand.grid() function in Python
# https://stackoverflow.com/a/12131385/1135316
def expandgrid(*itrs):
   product = list(itertools.product(*itrs))
   return {'Var{}'.format(i+1):[x[i] for x in product] for i in range(len(itrs))}




ltt= ['lt1','lt2']

methods=['method 1', 'method 2', 'method 3', 'method 4']
labels = ['label1','label2']
times = range(0,100,10)
data = pd.DataFrame(expandgrid(ltt,methods,labels, times, times))
data.columns = ['ltt','method','labels','dtsi','rtsi']
#data['nw_score'] = np.random.sample(data.shape[0])
data['nw_score'] = np.random.choice([0,1],data.shape[0])

labels_fill = {0:'red',1:'blue'}

def facet(data,color):
    data = data.pivot(index="dtsi", columns='rtsi', values='nw_score')
    g = sns.heatmap(data, cmap=ListedColormap(['red', 'blue']), cbar=False,annot=True)


for lt in data.ltt.unique():
    with sns.plotting_context(font_scale=5.5):
        g = sns.FacetGrid(data[data.ltt==lt],row="labels", col="method", size=2, aspect=1,margin_titles=False)
        g = g.map_dataframe(facet)
        g.add_legend()
        g.set_titles(template="")

        for ax,method in zip(g.axes[0,:],methods):
            ax.set_title(method, fontweight='bold', fontsize=12)
        for ax,label in zip(g.axes[:,0],labels):
            ax.set_ylabel(label, fontweight='bold', fontsize=12, rotation=0, ha='right', va='center')
        g.fig.suptitle(lt, fontweight='bold', fontsize=12)
        g.fig.tight_layout()
        g.fig.subplots_adjust(top=0.8) # make some room for the title

        g.savefig(lt+'.png', dpi=300)

lt1.png

enter image description here

lt2.png

enter image description here


Post a Comment for "Trouble With Saving Grouped Seaborn Facetgrid Heatmap Data Into A Directory"