2

I'd like to shift a pcolor plot along the x direction. But I'm not sure how to do it, as it's not as simple as using plot with a vector that specifies the x values

With this code:

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)
Z = np.random.rand(6, 5)

tk = list(range(0,10+1))

fig, ax = plt.subplots(figsize=(7.2, 2.3))

ax.pcolor(Z)
ax.set_xticks(tk)

plt.show()

It produced this plot:

enter image description here

However I want the heatmap shifted to the right to start at x = 2, for example, like the following plot:

enter image description here

What am I missing???

As a side question, if I swap lines 11 and 12 to:

ax.set_xticks(tk)
ax.pcolor(Z)

I get this plot with the x axis contracted to the range [0,5]. I'm not sure why setting ticks before adding pcolor would do that?

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
owl7
  • 308
  • 1
  • 3
  • 9

2 Answers2

3

One 'simple' way of achieving that is by just adding 2 empty (NaN) values to the Z:

Z = np.insert(Z, 0, np.nan, axis=1)
Z = np.insert(Z, 0, np.nan, axis=1)

Gives: enter image description here

0stone0
  • 34,288
  • 4
  • 39
  • 64
2

pcolor takes optional x and y arguments, which can be used to set the axes.

import matplotlib.pyplot as plt
import numpy as np

plt.close("all")

rng = np.random.default_rng()
Z = rng.random((6,5))

x0 = 2
y0 = 0
x = np.arange(x0, x0+Z.shape[1])
y = np.arange(y0, y0+Z.shape[0])

fig, ax = plt.subplots()
ax.pcolor(x, y, Z)
ax.set_aspect(1)
fig.tight_layout()
fig.show()

Alternatively, you can you pcolormesh, which the matplotlib documentation says is typically preferred. In this case, it is a drop-in replacement.

jared
  • 4,165
  • 1
  • 8
  • 31