1

I have an image that I would like to rotate. Namely, exchange the x and y axes. It is of a spectrogram. The basic code is

import matplotlib.pyplot as plt

Sxx, f, t, im = plt.specgram(dataArray, NFFT=2**8, Fs = 100, noverlap = 128)

plt.show()

This is what gets produced:

enter image description here

Does Python have a function that rotates the image 90 degrees as easily as the View function does in Matlab?

UPDATE

I've learned that plt.specgram can take all kwargs that imshow does. I still couldn't find any that would rotate the image, though. Anyone know?

UPDATE 2

I found here and confirmed here that Matlab has an argument option freqloc that can be used to exchange where the axes are drawn, but I can't locate the Python equivalent.

Lou
  • 1,113
  • 3
  • 9
  • 22

1 Answers1

1

You can use scipy rotate to rotate your data (from the array point of view). The following example:

import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage

X, Y = np.meshgrid(range(100), range(100))
im = X**2 + Y**2
imrot45 = ndimage.rotate(im, 45)
imrot90 = ndimage.rotate(im, 90)

f, (ax1, ax2, ax3) = plt.subplots(1, 3)

ax1.imshow(im, origin='lower', interpolation='nearest')
ax2.imshow(imrot45, origin='lower', interpolation='nearest')
ax3.imshow(imrot90, origin='lower', interpolation='nearest')
plt.show()

, results in this:

rotate imshow data for matplotlib plot

Depending on your data you may also want to try im.T (transpose) or numpy rot90.

I also recently, in another question, gave a recipe to rotate the figure if you prefer to do this. Check the following question:

Rotate a figure but not the legend

armatita
  • 12,825
  • 8
  • 48
  • 49
  • Thanks for the response. I can't see to get this to work with the `plt.specgram` function, though. – Lou Jun 13 '16 at 17:24
  • Sorry @Lou, it seems specgram has a behavior very different from the common matplotlib objects. I'm saying this because even with the second solution (where I rotate the figure) the plot remains the same. Have you considered using [imshow to build a specgram](http://www.frank-zalkow.de/en/code-snippets/create-audio-spectrograms-with-python.html). If the answer is not useful I'll delete it by tomorrow. Sorry for not being able to help more. – armatita Jun 13 '16 at 17:43
  • I'll take a look at that link. It seems he's building his own spectrogram function, which will probably be the way to go to have the axes how I want them. Thanks for your help! – Lou Jun 14 '16 at 20:04