2012-09-07 25 views
4

我已經在matplot庫中創建了一個圖並且我希望爲該圖添加一個插圖。我想繪製的數據保存在我用於其他數字的字典中。我在一個循環內找到這個數據,然後我再次爲這個子區域運行這個循環。下面是相關段:在matplot庫中創建插圖

leg = []  
colors=['red','blue'] 
count = 0      
for key in Xpr: #Xpr holds my data 
    #skipping over what I don't want to plot 
    if not key[0] == '5': continue 
    if key[1] == '0': continue 
    if key[1] == 'a': continue 
    leg.append(key) 
    x = Xpr[key] 
    y = Ypr[key] #Ypr holds the Y axis and is created when Xpr is created 
    plt.scatter(x,y,color=colors[count],marker='.') 
    count += 1 

plt.xlabel(r'$z/\mu$') 
plt.ylabel(r'$\rho(z)$') 
plt.legend(leg) 
plt.xlim(0,10) 
#Now I wish to create the inset 
a=plt.axes([0.7,0.7,0.8,0.8]) 
count = 0 
for key in Xpr: 
    break 
    if not key[0] == '5': continue 
    if key[1] == '0': continue 
    if key[1] == 'a': continue 
    leg.append(key) 
    x = Xpr[key] 
    y = Ypr[key] 
    a.plot(x,y,color=colors[count]) 
    count += 1 
plt.savefig('ion density 5per Un.pdf',format='pdf') 

plt.cla() 

奇怪的是,當我試圖移動插畫位置上,我仍然得到以前的插圖(那些從以前的代碼的運行)。我甚至試圖評論出a=axes([])線沒有任何明顯的。我附上了示例文件。爲什麼它以這種方式行事? A figure of the crooked output

+0

您是否在某些交互式環境中運行此代碼? – tacaswell

+0

我通過Emacs運行它。當我在終端中直接使用它時,有更好的結果 – Yotam

回答

3

簡單的答案是你應該使用plt.clf()清除數字,而不是當前軸。插入循環中還有一個break,這意味着所有代碼都不會運行。

當您開始做比使用單個軸更復雜的事情時,切換到使用面向matplotlib的OO接口是值得的。起初看起來可能更復雜,但您不必再擔心pyplot的隱藏狀態。您的代碼可以重寫爲

fig = plt.figure() 
ax = fig.add_axes([.1,.1,.8,.8]) # main axes 
colors=['red','blue'] 
for key in Xpr: #Xpr holds my data 
    #skipping over what I don't want to plot 
    if not key[0] == '5': continue 
    if key[1] == '0': continue 
    if key[1] == 'a': continue 
    x = Xpr[key] 
    y = Ypr[key] #Ypr holds the Y axis and is created when Xpr is created 
    ax.scatter(x,y,color=colors[count],marker='.',label=key) 
    count += 1 

ax.set_xlabel(r'$z/\mu$') 
ax.set_ylabel(r'$\rho(z)$') 
ax.set_xlim(0,10) 
leg = ax.legend() 

#Now I wish to create the inset 
ax_inset=fig.add_axes([0.7,0.7,0.3,0.3]) 
count =0 
for key in Xpr: #Xpr holds my data 
    if not key[0] == '5': continue 
    if key[1] == '0': continue 
    if key[1] == 'a': continue 
    x = Xpr[key] 
    y = Ypr[key] 
    ax_inset.plot(x,y,color=colors[count],label=key) 
    count +=1 

ax_inset.legend() 
+0

謝謝,當我開始這個「項目」時,我懶得做這個,現在文件太長了,我不能改變它。 – Yotam