Ahmed Alarbi
Ahmed Alarbi

Reputation: 33

plt.imshow is not working as it should be

so i have this code in python

import numpy as np
import matplotlib.pyplot as plt
M = np.zeros((490,1900))
fig, ax = plt.subplots()
plt.imshow(M, aspect='auto')
ax.set_ylabel('f2')
ax.set_xlabel('f1')
plt.xlim((0, 490))
plt.ylim((0, 1900))
x_range = np.arange(0, 490, step=50)
x_strings = [str(x+190) for x in x_range]
plt.xticks(x_range, x_strings)
y_range = np.arange(0, 1900, step=200)
y_strings = [str(y+1710) for y in y_range]
plt.yticks(y_range, y_strings)
plt.colorbar()
plt.ioff()
plt.show()

when i'm compiling it supposed to cover the whole area with the grid of zeros (M) that I've created, but instead it covers part of it as seen in this

picture

What i'm doing wrong here?

Upvotes: 0

Views: 141

Answers (1)

bglbrt
bglbrt

Reputation: 2098

I think you're simply confusing yourself when creating the matrix.

You're creating a matrix with 490 rows and 1900 columns when you're probably aiming to create a matrix with 1900 rows and 490 columns.

Your problem can be solved simply by changing the order with which you define your matrix M:

import numpy as np
import matplotlib.pyplot as plt
M = np.zeros((1900, 490)) # change is here
fig, ax = plt.subplots()
plt.imshow(M, aspect='auto')
ax.set_ylabel('f2')
ax.set_xlabel('f1')
plt.xlim((0, 490))
plt.ylim((0, 1900))
x_range = np.arange(0, 490, step=50)
x_strings = [str(x+190) for x in x_range]
plt.xticks(x_range, x_strings)
y_range = np.arange(0, 1900, step=200)
y_strings = [str(y+1710) for y in y_range]
plt.yticks(y_range, y_strings)
plt.colorbar()
plt.ioff()
plt.show()

Which yields:

enter image description here


You could of course also be changing the plot limits by inverting xlim and ylim.

Upvotes: 1

Related Questions