如何在Matplotlib中绘制二维结构化网格

时间:2019-12-13 17:09:09

标签: python numpy matplotlib mesh

我正在尝试使用matplotlib绘制结构化网格(请参见下图)

import numpy as np
import matplotlib.pyplot as plt

x, y = np.meshgrid(np.linspace(0,1, 11), np.linspace(0, 0.6, 7))

plt.scatter(x, y)
plt.show()

我有一个离散点,但是我不知道如何连接它们以获得类似的结果:

所需的结果是:

The desired result in this link

感谢您的帮助

3 个答案:

答案 0 :(得分:6)

为此,我将使用两个linecollection:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

x, y = np.meshgrid(np.linspace(0,1, 11), np.linspace(0, 0.6, 7))

plt.scatter(x, y)

segs1 = np.stack((x,y), axis=2)
segs2 = segs1.transpose(1,0,2)
plt.gca().add_collection(LineCollection(segs1))
plt.gca().add_collection(LineCollection(segs2))
plt.show()

enter image description here

另请参见How to plot using matplotlib (python) colah's deformed grid?

因为网格不变形,绘制单个线集会更有效,例如

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

x, y = np.meshgrid(np.linspace(0,1, 11), np.linspace(0, 0.6, 7))

segs1 = np.stack((x[:,[0,-1]],y[:,[0,-1]]), axis=2)
segs2 = np.stack((x[[0,-1],:].T,y[[0,-1],:].T), axis=2)

plt.gca().add_collection(LineCollection(np.concatenate((segs1, segs2))))
plt.autoscale()
plt.show()

答案 1 :(得分:3)

使用行np.transpose而不是plot()时,您可以scatter()拥有点。

import numpy as np
import matplotlib.pyplot as plt

x, y = np.meshgrid(np.linspace(0,1, 11), np.linspace(0, 0.6, 7))

plt.plot(x, y) # use plot, not scatter
plt.plot(np.transpose(x), np.transpose(y)) # add this here
plt.show()

您当然可以用c='k'将其涂成黑色 enter image description here

答案 2 :(得分:2)

IIUC,vlineshlines可以做到:

plt.vlines(np.linspace(0,1,11), 0, 0.6)
plt.hlines(np.linspace(0,0.6,7), 0, 1)

如果您已经拥有网格x,y

plt.vlines(x[0], *y[[0,-1],0])
plt.hlines(y[:,0], *x[0, [0,-1]])

出局:

enter image description here