Reputation: 5759
My DataFrame:
A B Up Down p
0 1 x A A 0.5
1 1 x T T 0.5
2 1 y G G 0.5
3 1 y C C 0.5
4 2 x A A 0.5
5 2 x T T 0.5
6 2 y G G 0.5
7 2 y C C 0.5
Code:
pd.DataFrame(
{'A': {0: 1,1: 1,2: 1,3: 1,4: 2,5: 2,6: 2,7: 2},
'B': {0: 'x',1: 'x',2: 'y',3: 'y',4: 'x',5: 'x',6: 'y',7: 'y'},
'Up': {0: 'A', 1: 'T', 2: 'G', 3: 'C', 4: 'A', 5: 'T', 6: 'G', 7: 'C'},
'Down': {0: 'A', 1: 'T', 2: 'G', 3: 'C', 4: 'A', 5: 'T', 6: 'G', 7: 'C'},
'p': {0: 0.5,1: 0.5,2: 0.5,3: 0.5,4: 0.5,5: 0.5,6: 0.5,7: 0.5}})
I am trying to use seaborn to plot out a heatmap of the above dataset. I can generate individual heatplots by manually looping through unique combinations of columns A
and B
but I would like to have them all in the same plot as sns.FacetGrid
enables.
I would like to generate individual heatplots for each combination of columns A
and B
. Each of those heatplots should use Up
as the y-axis and Down
as the x-axis. Values for each square within the heatplots should use column p
.
I would also like to be able to control the coloration for the range of p
values. The way I'm currently doing this is with something like the following:
from matplotlib.colors import LogNorm
lognorm = LogNorm(vmin=1.0 / (10.0 ** 200), vmax=1.0)
ax = sns.heatmap(df, norm = lognorm,)
Upvotes: 0
Views: 312
Reputation: 80309
You could create a FacetGrid
with 'A'
and 'B'
for rows and columns.
Then the axes_dict
of that FacetGrid
will contain a subplot (ax
) for each combination of 'A'
and 'B'
. These 'A'
and 'B'
can be used to take a subset of the dataframe as input for a pivot table.
g = sns.FacetGrid(df, row='A', col='B')
lognorm = LogNorm(vmin=1.0 / (10.0 ** 200), vmax=1.0)
for (a, b), ax in g.axes_dict.items():
sns.heatmap(df[(df['A'] == a) & (df['B'] == b)].pivot('Up', 'Down', 'p'), norm=lognorm, ax=ax)
ax.set_title(f'A={a} B={b}')
Upvotes: 2