2015-02-10 88 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