dagnic
dagnic

Reputation: 158

Draw several pcolormesh at different positions

I would like to draw a pcolormesh (here called qm2) with its left bottom pixel in a given position according to another pcolormesh (here called qm1).

I tried following:

import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':

    s_det = 4
    s_array = 14

    x_shift = 5
    y_shift = 5

    array = np.zeros([s_array, s_array])
    det = np.random.randint(0, 2, [s_det, s_det])

    qm1 = plt.pcolormesh(array, alpha=.0)
    qm2 = plt.pcolormesh(det, cmap='Oranges', edgecolor='black')
    qm2.set_offset_position('data')
    qm2.set_offsets = ([x_shift, y_shift])

    ax = plt.axes()
    ax.set_aspect('equal')
    plt.show()

But qm2 remains un-shifted.

pcolormesh

I expected something like this:

enter image description here

Upvotes: 3

Views: 624

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339250

Apparently the "data" argument is ignored, such that when doing

qm2.set_offset_position('data')
qm2.set_offsets([x_shift, y_shift])

the shift is still in pixels, not in data coordinates.

A workaround would be to define your own transform and add it in front of the existing ones:

trans = matplotlib.transforms.Affine2D().translate(x_shift, y_shift)
qm2.set_transform(trans + qm2.get_transform())

Complete example:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.transforms

s_det = 4
s_array = 14

x_shift = 5
y_shift = 5

array = np.zeros([s_array, s_array])
det = np.random.randint(0, 2, [s_det, s_det])

qm1 = plt.pcolormesh(array, alpha=.0)
qm2 = plt.pcolormesh(det, cmap='Oranges', edgecolor='black')

trans = matplotlib.transforms.Affine2D().translate(x_shift, y_shift)
qm2.set_transform(trans + qm2.get_transform())

ax = plt.gca()
ax.set_aspect('equal')
plt.show()

enter image description here

Upvotes: 0

Diziet Asahi
Diziet Asahi

Reputation: 40697

You have a typo in your code, the correct syntax on line 17 is

qm2.set_offsets([x_shift, y_shift])

however, although it does shift the position of qm2, it does not do so in data coordinates, and I don't really know why. You could play around with the values of x_shift and y_shift until you get to the desired position, but that's not very elegant.

One solution that I could offer is to explicitly specify the coordinates X,Y of your pcolormesh. The documentation for pcolormesh is not very explicit, but I believe it uses the same convention as pcolor.

s_det = 4
s_array = 14

x_shift = 5
y_shift = 5

array = np.zeros([s_array, s_array])
det = np.random.randint(0, 2, [s_det, s_det])

qm2_x = x_shift + np.arange(s_det+1)
qm2_y = y_shift + np.arange(s_det+1)

qm1 = plt.pcolormesh(array, alpha=.0)
qm2 = plt.pcolormesh(qm2_x, qm2_y, det, cmap='Oranges', edgecolor='black')

ax = plt.axes()
ax.set_aspect('equal')
plt.show()

enter image description here

Upvotes: 2

Related Questions