2015-02-10 208 views
1

我想在Python中使用Matplotlib绘制自定义的网格。使用Matplotlib绘制网格

我知道np.meshgrid函数,可以用它来获得我想连接的不同点的数组,但是我不确定如何绘制网格。

代码示例:

x = np.linspace(0,100,100) 
y = np.linspace(0,10,20) 
xv, yv = np.meshgrid(x, y) 

现在,我怎么能画出这个xv阵列的一个网格?

回答

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() 

exapmple

+0

还有'ax.vline'和'ax.hline' – tacaswell 2015-02-11 04:59:03

+0

这些块可以遮蔽吗? – Jonny 2015-02-11 18:46:03

+1

我添加了赛车旗帜风格块阴影,并使点缀的线条。 – 2015-02-14 12:51:40

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]) 

enter image description here

+0

谢谢,我不会说编码比接受的答案更快或更容易吗?或者你的意思是计算时间? – Jonny 2015-02-11 08:08:21

+0

我的意思是绘画时间。 – HYRY 2015-02-11 08:37:47

+0

啊,很好,谢谢! – Jonny 2015-02-11 08:38:22