Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logarithmic scale with imshow and "extent"?

I am having issues making a plot with a logarithmic y axis using imshow. My relevant code is as follows:

plt.imshow(power[channel], extent=(0,600,1,45), \
origin='lower', cmap='jet', aspect='auto', vmin=0, vmax=0.00025)
plt.colorbar()
plt.show(block=False)

Which gives the following plot:

Wavelet plot

My problem is that I need the "extent" parameter because otherwise the y axis labeling is incorrect in my case. However it seems that imshow (which includes the "extent" parameter) does not allow logarithmic axis scaling. Adding the line

plt.yscale('log')

gives me the warning "Images are not supported on non-linear axes."

Is there a way I can get logarithmic y axis scaling while keeping the "extent" function?

like image 719
Nico Autia Avatar asked Oct 21 '25 13:10

Nico Autia


1 Answers

I assume you'll have solved this by now, but I wanted to post an answer in case any one comes looking (like me). I was having a very similar problem trying to do plt.imshow() with a log y-axis: using extent was giving me the wrong axis labels.

My 'solution' was to use plt.pcolormesh() instead of plt.imshow(). You can pass an x and y meshgrid to this alongside your image and you can then set your log axes as I illustrate below.

import numpy as np
import matplotlib.pyplot as plt

# create the x coordinate
x = np.linspace(0, 50)
# create logarithmic y coordinate
y = np.logspace(1, 4)

X, Y = np.meshgrid(x, y)

# create random image data to use
im_data = np.random.rand(x.size, y.size)

ax = plt.gca()
ax.pcolormesh(X, Y, im_data)

# make y axis logarithmic
ax.set_yscale('log')
plt.show()

The output is:

script output

You can see it handles the log-axes nicely. Hopefully this helps you or anyone else who comes looking (I realise this doesn't answer your exact question but its a straight forward work-around).

like image 75
DarnTickLabels Avatar answered Oct 23 '25 05:10

DarnTickLabels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!