简体   繁体   English

使用 matplotlib 绘制带有切割单元的二维数组

[英]Plotting 2D array with cut cells with matplotlib

I want to plot using pcolor in matplotlib something akin to the JPEG in the link.我想 plot 在 matplotlib 中使用类似于链接中的 JPEG 的 pcolor 。 I am dealing with cut cells, which are grid cells in 2D that are split into two by some obstacle or barrier.我正在处理切割单元格,它们是 2D 中的网格单元格,被一些障碍物或障碍物分成两部分。 And I need to represent water state (height, velocity) in each of those split cells, so they should be able to be different colors.而且我需要在每个分裂单元中表示水 state(高度,速度),因此它们应该能够是不同的 colors。 I can plot the regular cells that are not split, but I am not sure how I can plot the cut cells.我可以 plot 未拆分的常规单元格,但我不确定如何 plot 切割单元格。

我想要的情节示例

You can first draw a normal colormesh, and then draw the second colormesh on top of it, clipped by a polygon:您可以先绘制一个普通的颜色网格,然后在其上绘制第二个颜色网格,由多边形裁剪:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

fig, ax = plt.subplots()

# first mesh
a = np.arange(4 * 5).reshape(4, 5)
ax.pcolormesh(a, cmap='PuBu', edgecolor='k', lw=2)

# polygon for clipping
poly = Polygon(xy=np.array([[.2, 4], [2, 0], [5, 4], [.2, 4]]), facecolor='none', edgecolor='orange', linewidth=2)
ax.add_patch(poly)

# second mesh
b = np.random.rand(4, 5)
mesh = ax.pcolormesh(b, cmap='spring', edgecolor='k', lw=2)
mesh.set_clip_path(poly)

ax.set_xticks([])
ax.set_yticks([])

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

示例图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM