parrott
parrott

Reputation: 378

Center specified tick labels for matplotlib's pcolomesh at the boxes

I do not understand, how to properly plot my heatmap (pcolormesh) with matplotlib. I want the tick's labels be centered below/beside the corresponding boxes - and only my given data, not some artificially extended ranges.

In the docs I found an example, which works slightly modified to floats just fine for me.

Z = []
for i in range(1, 7):
    Z.append([j*i for j in range(1, 11)])
Z = np.asarray(Z)
x = np.linspace(0.1, 1.0, num=10)
y = np.linspace(0.1, 0.6, num=6)
fig, ax = plt.subplots()
ax.pcolormesh(x, y, Z, vmin=np.min(Z), edgecolors='w', linewidths=0.5, vmax=np.max(Z), shading='auto')
plt.show()

The result prints the ticks centered at the boxes, which is exactly what I want. enter image description here

But as soon as I use my own data it ends up with some weird behaviour

data = pd.DataFrame(index=[0, 0.25, 0.5], data={0: [31.40455938, 101.43291831, 101.67128077], 0.25: [31.40455938, 89.81448724, 99.65066293], 0.5: [31.40455938, 57.01406046, 101.47536496]})
x = data.columns.astype(np.float64).to_numpy()
y = data.index.astype(np.float64).to_numpy()
z = data.to_numpy()
cmap = LinearSegmentedColormap.from_list('G2R', ["green", "red"])
fig, ax = plt.subplots()
ax.pcolormesh(x, y, z, shading='auto', cmap=cmap, edgecolors='w', linewidths=0.5, vmin=0, vmax=100)  # shading='gouraud'
ax.set_title('not what i want')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()

enter image description here

How do I get my heatmap to simply plot the given floats as centered tick labels without those unwanted floats? I literally want to specify my tick labels (floats or strings) to be shown centered to the boxes. I would assume there must be a way, to specify a list or array as tick labels. How do I accomplish that?

Upvotes: 1

Views: 1482

Answers (1)

Zephyr
Zephyr

Reputation: 12496

After plotting the pcolormesh you can set x and y tick with matplotlib.axes.Axes.set_xticks and matplotlib.axes.Axes.set_yticks respectively:

ax.pcolormesh(x, y, z, shading='auto', cmap=cmap, edgecolors='w', linewidths=0.5, vmin=0, vmax=100)  # shading='gouraud'
ax.set_xticks(data.columns)
ax.set_yticks(data.index)

enter image description here

Upvotes: 1

Related Questions