我正在尝试使用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()
我有一个离散点,但是我不知道如何连接它们以获得类似的结果:
所需的结果是:
感谢您的帮助
答案 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()
另请参见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()
答案 2 :(得分:2)