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:
1 Answer 1
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
- Also you can set values at start (left-down corner) just tricking a little more:
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:
Comments
Explore related questions
See similar questions with these tags.
plt.xlim((-0.5,9.5))andplt.ylim((-0.5,9.5)). Last if you really need the numbers to be between 1 and 10 you could use xticks and yticks:plt.xticks(np.arange(10), np.arange(1,11))andplt.yticks(np.arange(10), np.arange(1,11))Note that if you want the tick to start at left-down corner of pixel you can play with the first arange in ticks (i think it must benp.arange(-0.5,9.5,1)but im not sure)