iayork
iayork

Reputation: 6699

Seaborn heatmap with numerical axes

I want to overlay a heatmap with a second chart (a KDEplot, but for this example I'll use a scatterplot, since it shows the same issue).

Seaborn heatmaps have categorical axes, so overlaying a chart with numerical axes doesn't line up the two charts properly.

Example:

df = pd.DataFrame({2:[1,2,3],4:[1,3,5],6:[2,4,6]}, index=[3,6,9])
df

    2   4   6
3   1   1   2
6   2   3   4
9   3   5   6

fig, ax1 = plt.subplots(1,1)
sb.heatmap(df, ax=ax1, alpha=0.1)

enter image description here

Overlaying this with a scatterplot:

fig, ax1 = plt.subplots(1,1)
sb.heatmap(df, ax=ax1, alpha=0.1)
ax1.scatter(x=5,y=5, s=100)
ax1.set_xlim(0,10)
ax1.set_ylim(0,10)

Is there a way to convince the heatmap to use the column and index values as numerical values?

enter image description here

Upvotes: 1

Views: 3955

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339200

You cannot "convince" heatmap not to produce a categorical plot. Best use another image plot, which uses numerical axes. For example, use a pcolormesh plot. The assumption is of course that the columns and rows are equally spread. Then,

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

df = pd.DataFrame({2:[1,2,3],4:[1,3,5],6:[2,4,6]}, index=[3,6,9])

c = np.array(df.columns)
x = np.concatenate((c,[c[-1]+np.diff(c)[-1]]))-np.diff(c)[-1]/2.
r = np.array(df.index)
y = np.concatenate((r,[r[-1]+np.diff(r)[-1]]))-np.diff(r)[-1]/2.
X,Y = np.meshgrid(x,y)


fig, ax = plt.subplots(1,1)
pc = ax.pcolormesh(X,Y,df.values, alpha=0.5, cmap="magma")
fig.colorbar(pc)
ax.scatter(x=5,y=5, s=100)
ax.set_xlim(0,10)
ax.set_ylim(0,10)

plt.show()

produces

enter image description here

Upvotes: 5

Related Questions