Search code examples
pythonpandasseabornheatmapfacet-grid

Access current column and row information in Seaborn FacetGrid


I am plotting a FacetGrid of heatmaps with the seaborn package in python.

Now I want to overlay each heatmap with a hatch depending on the heatmap-tile value following this example:

adding hatches to seaborn heatmap plot

My function, which defines if a cell is hatched or not depends on the row and column information of the FacetGrid

def draw_heatmap(*args, **kwargs):
    kwargs.pop('color')
    data = kwargs.pop('data')
    d = data.pivot(index=args[1], columns=args[0], values=args[2])
    d = d.sort_index(ascending=False)
    sns.heatmap(d, **kwargs)


d = np.array(
    np.meshgrid(np.arange(1, 6, 1),
                np.arange(6, 11, 1),
                np.arange(1, 6, 1),
                np.arange(6, 11, 1))).T.reshape(-1, 4)
d = np.c_[d, np.random.randint(1, 5, 625)]
df = pd.DataFrame(d, columns=['a', 'b', 'c', 'd', 'e'])
fg = sns.FacetGrid(df,
                   col='b',
                   row='a',
                   margin_titles=True,
                   height=5,
                   aspect=1)
fg = fg.map_dataframe(draw_heatmap,
                      'c',
                      'd',
                      'e',
                      cbar=False,
                      cmap='viridis',
                      annot=True,
                      fmt=".0f",
                      linewidths=.5)

Now, depending on the values of 'b', 'a' and 'values', where 'b', 'a' are rows and columns of the FacetGrid and 'values' are the values of the pivot tabel in the draw_heatmap function, I want to apply a mask.

# fgA and fgB are the input values coming from the FacetGrid
hatch = data.stack().to_frame().apply(lambda x: myFunc(fgA, fgB, x.name[0], x.name[1]), axis=1).unstack()
x = np.arange(len(data.columns)+1)
y = np.arange(len(data.index)+1)
zm = np.ma.masked_less(hatch.values, 5)
fig, ax = plt.subplots()
sns.heatmap(w, cmap='viridis', annot=True, fmt=".0f", linewidths=.5, ax=ax)
ax.pcolor(x, y, zm, hatch='//', alpha=0.)

How can I realize this and access the FacetGrid information while plotting the single heatmaps?

Thanks


Solution

  • You can get the axes object within the FacetGrid using the axes attribute. It's an array of all the axes in your FacetGrid.

    fg.axes[b, a].pcolor(x, y, zm, hatch='//', alpha=0.)