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 ?
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()
