我想在Python中使用Matplotlib绘制一个自定义网格。
我知道np.meshgrid
函数,可以使用它来获取我想要连接的不同点的数组,但我不确定如何绘制网格。
代码示例:
x = np.linspace(0,100,100)
y = np.linspace(0,10,20)
xv, yv = np.meshgrid(x, y)
现在,我如何绘制此xv
数组的网格?
答案 0 :(得分:3)
您可以使用grid()
打开/关闭网格,但只能让网格线在轴上打勾,所以如果您想要手工制作,那么:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
xs = np.linspace(0, 100, 51)
ys = np.linspace(0, 10, 21)
ax = plt.gca()
# grid "shades" (boxes)
w, h = xs[1] - xs[0], ys[1] - ys[0]
for i, x in enumerate(xs[:-1]):
for j, y in enumerate(ys[:-1]):
if i % 2 == j % 2: # racing flag style
ax.add_patch(Rectangle((x, y), w, h, fill=True, color='#008610', alpha=.1))
# grid lines
for x in xs:
plt.plot([x, x], [ys[0], ys[-1]], color='black', alpha=.33, linestyle=':')
for y in ys:
plt.plot([xs[0], xs[-1]], [y, y], color='black', alpha=.33, linestyle=':')
plt.show()
答案 1 :(得分:1)
使用LineCollection
:
import pylab as pl
from matplotlib.collections import LineCollection
x = np.linspace(0,100,100)
y = np.linspace(0,10,20)
pl.figure(figsize=(12, 7))
hlines = np.column_stack(np.broadcast_arrays(x[0], y, x[-1], y))
vlines = np.column_stack(np.broadcast_arrays(x, y[0], x, y[-1]))
lines = np.concatenate([hlines, vlines]).reshape(-1, 2, 2)
line_collection = LineCollection(lines, color="red", linewidths=1)
ax = pl.gca()
ax.add_collection(line_collection)
ax.set_xlim(x[0], x[-1])
ax.set_ylim(y[0], y[-1])