Ohjeah
Ohjeah

Reputation: 1307

heatmap with variable datapoint width

I want to plot the coefficients of a linear model over time.

On the y-axis you have the i-th feature of my model, on the x-axis is time and the value of the i-th coefficient is color coded.

In my example, the coefficients are constant from 0 to t1, t1 to t2 and so on. The intervals are not equally sized. Currently I circumvent this by creating many points spaced by delta t:

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

xi1 = [0, 1, 2]
t1 = range(4)

xi2 = [1, 1, 2]
t2 = range(5, 8)

data= np.vstack([xi1]*len(t1) + [xi2]*len(t2)).T
sns.heatmap(data)

enter image description here

Is there a way to do this more efficiently (without creating the redundant information)? I am also looking to have the right x-axis labels according to my t values.

Upvotes: 2

Views: 320

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339200

You can use a matplotlib pcolormesh.

import matplotlib.pyplot as plt
import numpy as np

a = [[0,1],[1,1],[2,2]]
y = [0,1,2,3]
x = [0,5,8]
X,Y = np.meshgrid(x,y)
Z = np.array(a)

cmap = plt.get_cmap("RdPu", 3)
plt.pcolormesh(X,Y,Z, cmap=cmap)
plt.gca().invert_yaxis()
plt.colorbar(boundaries=np.arange(-0.5,3), ticks=np.unique(Z))
plt.show()

enter image description here

Upvotes: 3

Related Questions