Tick labels at regular intervals

Viewed 321

I would like to replicate the following heatmap, and I'm quite close. I'm new to python and I don't get the axes and the coloring right.

def fun(C_1, C_2):
    return np.multiply(C_1, C_2)

C_1 = np.linspace(-2,2,100)
C_2 = np.linspace(-2,2,100)

# filling the heatmap, value by value
fun_map = np.empty((C_1.size, C_2.size))
for i in range(C_1.size):
    for j in range(C_2.size):
        fun_map[i,j] = fun(C_1[i], C_2[j])

sns.heatmap(fun_map)

This produces the following plot. What I don't know is how to get the axis right, i.e. C_1 and C_2 instead of the indices.

And also, how do I only show the 0.5 steps, i.e. -2, -1.5, etc.?

enter image description here

Any help would be appreciated.

1 Answers

To set the ticks on both axes you could either use set and specify the xticklabels and yticklabels. For the numerical tick labels to be at regular intervals though, we'll need to work a little on the label sequences. Here's one approach:

def show_at_intervals(seq, interval, decimals=1):
    x = np.copy(seq)
    low, high = x.min(), x.max()
    ar = np.arange(low,high,interval)
    replate_at = np.searchsorted(x, ar)
    new_ticks = np.full(x.shape, '', dtype=f'U{4+decimals}')
    new_ticks[replate_at] = x[replate_at].round(decimals)
    return new_ticks

Then just specify the sequences we want on both axes ad the new intervals (note that the outer product can directly be obtained using np.multiply.outer):

g = sns.heatmap(np.multiply.outer(C_1, C_2), 
                xticklabels=True, yticklabels=True)
_ = g.set(xticklabels = show_at_intervals(C_1, 0.5),
          yticklabels = show_at_intervals(C_1, 0.5))

enter image description here

Or for instance for a spacing of .5 on the x-axis and 0.2 on the y-axis:

g = sns.heatmap(np.multiply.outer(C_1, C_2))
_ = g.set(xticklabels = show_at_intervals(C_1, .5),
          yticklabels = show_at_intervals(C_2, 0.2))

enter image description here

Related