Skip to main content
 首页 » 编程设计

python之在不同位置画几个pcolormesh

2025年01月19日15lidabo

我想根据另一个 pcolormesh(此处称为 qm1)在给定位置绘制一个 pcolormesh(此处称为 qm2),其左下角像素位于给定位置。

我试过以下:

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() 

但是 qm2 保持不变。

我期待这样的事情:

请您参考如下方法:

你的代码有错别字,第 17 行的正确语法是

qm2.set_offsets([x_shift, y_shift]) 

然而,虽然它确实移动了 qm2 的位置,但它并没有在数据坐标中这样做,我真的不知道为什么。您可以调整 x_shift 和 y_shift 的值,直到到达所需的位置,但这不是很优雅。

我可以提供的一种解决方案是显式指定 pcolormesh 的坐标 X、Y。 documentation for pcolormesh不是很明确,但我相信它使用了 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()