Reputation: 1274
I have some z=f(x,y) data that I would like to display in a heat map. So I am using np.meshgrid
to create a (x,y)-grid and then call pcolormesh
. However the ticks are not centered for each "tile" that correspond to a data point -- in the docs, I did not find any instructions on how to center the ticks for each tile so that I can immediately read off the corresponding value. Any ideas?
In the image attached for instance, it is not clear to which x-value the tick corresponds.
Upvotes: 4
Views: 9584
Reputation: 339380
In a pcolormesh the grid is defined by the edge values. In the following example the value of 6 in the lower left corner is the value between 0 and 1 in each dimension. I think this is perfectly understandable to everyone.
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
x = np.arange(5)
y = np.arange(3)
X,Y = np.meshgrid(x,y)
Z = np.random.randint(1,9, size=(2,4))
plt.pcolormesh(X,Y,Z)
plt.show()
Now if you want to (only) have the ticks in the middle of the cell, you can set them as follows
plt.xticks(x[:-1]+0.5)
plt.yticks(y[:-1]+0.5)
If the lower left pixel actually does not correspond to the data between 0 and 1, but to the data at 0, the grid is 'wrong'; a solution would be to fix it by translating it by half the pixel width.
plt.pcolormesh(X-0.5,Y-0.5,Z)
As above, the ticks could be adapted to show only certain numbers, using plt.xticks
.
Upvotes: 6