OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

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

  • Thread starter Thread starter jr2023
  • Start date Start date
J

jr2023

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

Code:
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 as 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.
<p>Let's say I wanted to plot a <code>numpy</code> matrix as an image, so I used <code>matplotlib</code>'s <code>imshow()</code> function.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy
a = numpy.random.random((16,16))
plt.imshow(a)
<matplotlib.image.AxesImage object at 0x000001F3EE029DD0>
plt.show()
</code></pre>
<p><a href="https://i.sstatic.net/JpTSgHr2.png" rel="nofollow noreferrer">imshow output for a random matrix.</a></p>
<p>I have some non-linear function that takes an integer as 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 <code>Matplotlib</code>?</p>
<p>I tried to create a list comprehension;<br />
<code>ticks = [f(x) for x in range(0,16,2)]</code></p>
<p>and then set the y ticks based on <a href="https://stackoverflow.com/questions/49471424/add-custom-tick-with-matplotlib">this post:</a></p>
<p><code>fig, ax = pyplot.subplots()</code></p>
<p><code>ax.set_yticklabels(ticks)</code></p>
<p>And ended up with two different figures, neither of which had the labels I wanted.</p>
 

Latest posts

Top