1

I'd like to create a seaborn heatmap which has also scatter plot color points. I'd like the final result to use the grid of the scatter plot, with the squares of the heatmap being "centered" on the scatter points.

Unfortunately, I don't find how to share scales between the two layers, as shown in the example below.

What can I do?

Thanks a lot for your help.

%matplotlib inline
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

npoints = 3
x = np.tile(np.arange(npoints), npoints)
df = pd.DataFrame({'x': np.tile(np.arange(npoints), npoints), 'y': np.repeat(np.arange(npoints), npoints)})

df['z'] = 0
df.loc[df['x'] == df['y'], 'z'] = df.loc[df['x'] == df['y'], 'x']
df['c'] = np.random.choice(np.arange(3) + 1, df.shape[0])
df.loc[df['x'] != df['y'], 'c'] = 0

sns.heatmap(df[['x', 'y', 'z']].set_index(['x', 'y'])['z'].unstack())
plt.gca().set_title('Heatmap only')

df.plot(x='x', y='y', color=df['c'], kind='scatter')
plt.gca().set_title('Scatter points only')

fig, ax = plt.subplots()
sns.heatmap(df[['x', 'y', 'z']].set_index(['x', 'y'])['z'].unstack(), ax=ax)
df.plot(x='x', y='y', ax=ax, color=df['c'], kind='scatter')
ax.set_title('Heatmap and scatter points - scales problem')

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

1
  • 1
    This question is a little misphrased because there isn't really a seaborn "layer" in the plot, seaborn only ever adds matplotlib objects. Your issue isn't about sharing scales, it is in realizing that the cells in the heatmap span integral values (look at, e.g.` ax.get_xticks()`). Commented Nov 4, 2016 at 18:34

1 Answer 1

1

A workaround would be to shift your scatter data by 0.5:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

npoints = 3
x = np.tile(np.arange(npoints), npoints)
df = pd.DataFrame({'x': np.tile(np.arange(npoints), npoints), 'y': np.repeat(np.arange(npoints), npoints)})

df['z'] = 0
df.loc[df['x'] == df['y'], 'z'] = df.loc[df['x'] == df['y'], 'x']
df['c'] = np.random.choice(np.arange(3) + 1, df.shape[0])
df.loc[df['x'] != df['y'], 'c'] = 0

fig, ax = plt.subplots()
qp = sns.heatmap(df[['x', 'y', 'z']].set_index(['x', 'y'])['z'].unstack(), ax=ax)
# df.plot(x='x', y='y', ax=ax, color=df['c'], kind='scatter')
ax.scatter(df['x']+0.5,df['y']+0.5,c=df['c'])

ax.set_title('Heatmap and scatter points - scales problem')

plt.show()

result:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.