2012-07-26 39 views
1

當我嘗試在兩個子圖中顯示LineCollections時,都不顯示任何子圖。當我只在第一個顯示它時,它才起作用。我怎樣才能讓它在兩者中顯示?在matplotlib子圖中顯示LineCollections

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

# Unique points 
points = numpy.random.randint(0,2000, (1000, 2)) 
points = numpy.vstack([numpy.array(u) for u in set([tuple(p) for p in points])]) 

# Delaunay edges 
centers, edges, tris, neighb = matplotlib.delaunay.delaunay(points[:,0], points[:,1]) 

# LineCollection of edges 
lc_edges = LineCollection(points[edges]) 

# 1x2 subplots 
fig,(ax) = plt.subplots(1, 2, figsize=(12,16)) 

ax1 = plt.subplot(211, aspect='equal', xlim=[points[:,0].min()- 100, points[:,0].max() + 100], ylim=[points[:,1].min() - 100, points[:,1].max() + 100]) 
plt.title("First plot") 
plt.gca().add_collection(lc_edges) 
plt.scatter(points[:,0], points[:,1]) 

ax2 = plt.subplot(212, aspect='equal', xlim=[points[:,0].min()- 100, points[:,0].max() + 100], ylim=[points[:,1].min() - 100, points[:,1].max() + 100]) 
plt.title("Second plot") 
#plt.gca().add_collection(lc_edges) 
plt.scatter(points[:,0], points[:,1]) 

fig.savefig('myfile.png', dpi=250) 
plt.close() 

編輯: 「能LineCollection對象被重新使用」

真正的問題是

+0

爲什麼你想重新使用行集合,而不是正在爲第二個圖一個新的? – tacaswell 2012-07-26 14:28:44

+0

因爲在我的真實情況下它是巨大的,我不想重置我爲它定義的屬性。我不能重新使用它嗎? – Benjamin 2012-07-26 14:42:14

+1

我懷疑問題是'LineCollection'不會做你想要的。它有一個屬性'axes',它指定了與哪個軸關聯(並且在創建LineCollection時設置爲None)。將'LineCollection'添加到第二個軸時,lc_edges'已記錄的軸發生了變化(並且它被添加爲'ax2'的子節點),但我敢肯定,變化不會一直傳播到對象堆棧中並且有些事情變得困惑。對不起,我沒有更好的答案。 – tacaswell 2012-07-26 14:47:55

回答

1

您可以使用複製模塊製作lc_edges的卷影副本。 lc_edges2和lc_edges都將使用相同的路徑列表,您可以通過以下方式進行確認:lc_edges._paths is lc_edges2._paths

import numpy 
import matplotlib.delaunay 
from matplotlib import pyplot as plt 
from matplotlib.collections import LineCollection 
import copy 

# Unique points 
points = numpy.random.randint(0,2000, (1000, 2)) 
points = numpy.vstack([numpy.array(u) for u in set([tuple(p) for p in points])]) 

# Delaunay edges 
centers, edges, tris, neighb = matplotlib.delaunay.delaunay(points[:,0], points[:,1]) 

# LineCollection of edges 
lc_edges = LineCollection(points[edges]) 
lc_edges2 = copy.copy(lc_edges) 
# 1x2 subplots 
fig,(ax) = plt.subplots(1, 2, figsize=(12,16)) 

ax1 = plt.subplot(211, aspect='equal', xlim=[points[:,0].min()- 100, points[:,0].max() + 100], ylim=[points[:,1].min() - 100, points[:,1].max() + 100]) 
plt.title("First plot") 
plt.gca().add_collection(lc_edges) 
plt.scatter(points[:,0], points[:,1]) 

ax2 = plt.subplot(212, aspect='equal', xlim=[points[:,0].min()- 100, points[:,0].max() + 100], ylim=[points[:,1].min() - 100, points[:,1].max() + 100]) 
plt.title("Second plot") 

plt.gca().add_collection(lc_edges2) 
plt.scatter(points[:,0], points[:,1]) 

plt.show() 

結果是這樣的:

LineCollection result