matplotlib 基于色彩Map图绘制填充单元格的角网格

0md85ypi  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(107)

我想在两个坐标系之间进行转换,并相应地显示填充的单元格,如下所示:-

我已经能够创建下面的填充网格的方式,我想要的,但我不太清楚如何绘制角转换网格。

import numpy as np
import matplotlib.pyplot as plt

z_min = 10
z_max = 100
n_zcells = 10
z_array = np.linspace(z_min, z_max, n_zcells)

u_min = -9.5
u_max = 9.5
n_ucells = 15
u_array = np.linspace(u_min, u_max, n_ucells)

[u_grid, z_grid] = np.meshgrid(u_array, z_array)

# %% Represent Polar Grid in Cartesian Coordinates

f = 5   # Focal length in pixels
B = 10  # Baseline in cm

# u = fX/Z; Equation for Camera to Pixel Coordinates

x_grid = u_grid*z_grid/f

# %% Desired Grid Points

plt.figure()
plt.subplot(2,1,1)
plt.scatter(x_grid, z_grid)
plt.xlabel('Lateral Distance (cm)')
plt.ylabel('Depth (cm)')
plt.subplot(2,1,2)
plt.scatter(u_grid, z_grid) 
plt.xlabel('Pixel Column ')
plt.ylabel('Depth (cm)')
plt.show()

# %%  Filled Grid Cell Colours

filled_colours = np.random.rand(n_zcells-1,n_ucells-1) # No. of cells will be 1 less than no. of grid points
plt.imshow(filled_colours, cmap=plt.get_cmap('gray'), origin='lower')

有没有合适的方法来填充直角坐标系中的角网格,用矩形网格的颜色填充?我试着查看plt.fill()和plt.contour(),但是没有找到合适的方法。感谢任何帮助。

a2mppw5e

a2mppw5e1#

我有一个基于@Thijs在评论中建议的补丁方法的工作解决方案,我对每个多边形逐块进行处理,并填充在色彩Map表输出中获得的颜色。

####### Continuing from the code snippet posted in the question #######
from matplotlib.patches import Polygon

# %%  Filled Grid Cell Colours
filled_colours = np.random.rand(n_zcells-1,n_ucells-1) # No. of cells will be 1 less than no. of grid points 

fig3, (ax1, ax2) = plt.subplots(ncols=2)
ax1.imshow(filled_colours, cmap=plt.get_cmap('gray'), origin='lower')
ax1.set_title('Occupancy Grid in Polar Coordinates', fontweight="bold")
ax1.set_xlabel('Pixel Column u (px)')
ax1.set_ylabel('Depth z (cm)')
ax1.set_anchor('C')

ax2.plot(x_grid, z_grid, color = "k", linewidth = 0.5)
cmap = plt.cm.get_cmap('gray')
colors = cmap(filled_colours/np.max(filled_colours))

# Block by Block Polygon Coloured Patch Added 
for i in range(n_zcells-1):
    for j in range(n_ucells-1):
        v1 = [x_grid[i,j], z_grid[i,j]]
        v2 = [x_grid[i+1,j], z_grid[i+1,j]]
        v3 = [x_grid[i+1,j+1], z_grid[i+1,j+1]]
        v4 = [x_grid[i,j+1], z_grid[i,j+1]]
        color_cell = colors[i,j,:]
        # v1-v4 are the Polygon vertices in cartesian coordinates
        ax2.add_patch(Polygon([v1, v2, v3, v4], color = color_cell))        

ax2.set_title('Occupancy Grid in Cartesian Coordinates', fontweight="bold")
ax2.set_xlabel('Lateral Distance x(cm)')
ax2.set_ylabel('Depth z (cm)')
ax2.set_anchor('C')

  
# creating ScalarMappable
sm = plt.cm.ScalarMappable(cmap=cmap,)
sm.set_array([])

plt.colorbar(sm, ax=ax2)
plt.show()

输出如下所示:-x1c 0d1x

相关问题