Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I label ticks in matplotlib imshow() using a custom method?

Let’s say I wanted to plot a numpy matrix as an image, so I used matplotlib‘s imshow() function.

>>> import matplotlib.pyplot as plt
>>> import numpy
>>> a = numpy.random.random((16,16))
>>> plt.imshow(a)
<matplotlib.image.AxesImage object at 0x000001F3EE029DD0>
>>> plt.show()

imshow output for a random matrix.

I have some non-linear function that takes an integer input and outputs an integer. On the y-axis, I want the labels to be in the same place (that specific place in the numpy array) but I want them first to be converted by this function. On the y-axis, I’d like to see f(0), f(2) … f(14) instead of 0,2…14. Is this possible with matplotlib ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to create a list comprehension;
ticks = [f(x) for x in range(0,16,2)]

and then set the y ticks based on this post:

fig, ax = pyplot.subplots()

ax.set_yticklabels(ticks)

And ended up with two different figures, neither of which had the labels I wanted.

>Solution :

You can use yticks():

import matplotlib.pyplot as plt
import numpy as np


f = lambda x: x ** 2
a = np.random.random((16, 16))
plt.imshow(a)
ticks = [f(x) for x in range(0, 16, 2)]
plt.yticks(ticks=range(0, 16, 2), labels=ticks)
plt.show()

Prints

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading