Reputation: 379
I am trying to visualize a random array with the square shape of (10, 10) in Python using matplotlib (3.5 version). I am also including the xaxis and yaxis ticks, but the ticks for 10 show empty data. Does anyone know how to sort it out?
Here's my code:
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.pylab as pylab
params = {'legend.fontsize': 'medium',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
arr = np.random.rand(10, 10)
plt.imshow(arr)
plt.ylim(0, 10)
plt.xlim(0, 10)
plt.xticks(np.arange(0.0, 11.0, 1.0))
plt.yticks(np.arange(0.0, 11.0, 1.0))
plt.show()
This is the produced image:
Upvotes: 2
Views: 2338
Reputation: 1725
As other users pointed, Python arrays start indexing in '0'. You could trick the ticks to show the values you want:
create data to plot
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.pylab as pylab
params = {'legend.fontsize': 'medium',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
arr = np.random.rand(10, 10)
Then you can use plt.xticks(tickPosition,tickValues)
and same with yticks. Note that every number point to the center of every value in your image so also you have to change your lim positions:
plt.figure()
plt.imshow(arr)
plt.ylim(-0.5, 9.5) #to show no blank spaces
plt.xlim(-0.5, 9.5) #to show no blank spaces
plt.xticks(np.arange(0, 10),np.arange(1, 11)) #trick the ticks
plt.yticks(np.arange(0, 10),np.arange(1, 11))
This will give you the next figure
plt.xticks(np.arange(-0.5, 9.5),np.arange(1, 11))
plt.yticks(np.arange(-0.5, 9.5),np.arange(1, 11))
this will give you this result:
Upvotes: 1