zzzbbx
zzzbbx

Reputation: 10141

How to relabel axis ticks for a matplotlib heatmap

I am following this example to produce a heat map. Would it be possible to relabel the values over the X-axis, and add a constant to it.

Instead of 0, 1, 2, 3, 4 on the x-axis, I would like to have, for example, 5, 6, 7, 8, 9.

Upvotes: 3

Views: 14444

Answers (3)

Gabriel
Gabriel

Reputation: 10884

You can label the x and y axes by using the keyword argument extent in the calls to imshow. Here is some documentation,

extent : scalars (left, right, bottom, top), optional, default: None
Data limits for the axes.  The default assigns zero-based row,
column indices to the `x`, `y` centers of the pixels.

working off the example you linked, you can do the following,

import matplotlib.pyplot as plt
import numpy as np

A = np.random.rand(5, 5)
plt.figure(1)
plt.imshow(A, interpolation='nearest')
plt.grid(True)

left = 4.5
right = 9.5
bottom = 4.5
top = -0.5
extent = [left, right, bottom, top]

plt.figure(2)
plt.imshow(A, interpolation='nearest', extent=extent)
plt.grid(True)

plt.show()

enter image description here

enter image description here

This will change only the x-axis labels. Note that you have to account for the fact that the default labels the pixels while extent labels the whole axis (hence the factors of 0.5). Also note that the default labelling of the y-axis in imshow increases from top to bottom (going from 0 at the top to 4 at the bottom), this means our bottom will be larger than our top variable.

Upvotes: 2

user2489252
user2489252

Reputation:

You can simple add the constant via for-loop or list comprehension and use it as new axis label, for example:

import matplotlib.pyplot as plt

CONST = 10

x = range(10)
y = range(10)
labels = [i+CONST for i in x]

fig, ax = plt.subplots()

plt.plot(x, y)
plt.xlabel('x-value + 10')


# set ticks followed by setting labels
ax.set_xticks(range(10))
ax.set_xticklabels(labels)

plt.show()

enter image description here

I added it to my matplotlib gallery in IPython notebooks here with other examples if it is useful:

Upvotes: 1

Pierz
Pierz

Reputation: 8118

If you just want to relabel the current plot (click on it to select it) you use the xticks() function (Note the arange() upper limit needs to be one more than the desired maximum) - e.g. from iPython/Python:

xticks(arange(0,5),arange(5,10))

If you wanted to modify the python script file then you would use:

plt.xticks(arange(0,5),arange(5,10))

Upvotes: 0

Related Questions