Reputation: 1263
I'm creating a heatplot and want to label the equally-spaced x-axis tickmarks using values from a list. The list values are floats, given in increasing order, but not uniformly spaced.
Here's what I've tried for a heatmap corresponding to a 5-by-20 matrix using a list of four tickmark labels: [1.2,2.3,4.7,8.3]:
import numpy as np
import matplotlib.pyplot as plt
M=np.random.rand(5,20)
fig,ax=plt.subplots()
pos=ax.imshow(M,aspect='auto',cmap='jet')
fig.colorbar(pos, ax=ax)
labels=[1.2, 2.3, 4.7,8.3]
ax.xaxis.set_major_locator(plt.MaxNLocator(len(labels)))
ax.set_xticklabels([t for t in labels])
plt.show()
The resulting graph has four equally-spaced tickmarks on the horizontal axis. The first three are labelled, from left to right, as 2.3, 4.7, and 8.3. The last tickmark has no value, and the first value of 1.2 does not appear in the lower-left corner as desired. I can't seem to determine how to correct this.
Upvotes: 1
Views: 69
Reputation: 995
Looks like set_xticks
is what you're missing. The positions can be created equidistant by just using range
and setting the step size:
import numpy as np
import matplotlib.pyplot as plt
num_cols = 20
M = np.random.rand(5, num_cols)
fig,ax=plt.subplots()
pos=ax.imshow(M, aspect='auto',cmap='jet')
fig.colorbar(pos, ax=ax)
labels = [1.2, 2.3, 4.7, 8.3]
pos = range(0, num_cols, num_cols // len(labels))
ax.xaxis.set_major_locator(plt.MaxNLocator(len(labels)))
ax.set_xticks(pos)
ax.set_xticklabels(labels)
plt.show()
Output:
Per your comment above, for a 5-by-400 matrix, you'd just change the following:
num_cols = 400
labels = [60, 280, 410, 756]
which produces:
Upvotes: 1