2011-02-23 109 views
1

這是我第一次使用python繪圖,我想我不太理解matplotlib中對象之間的交互。我有以下模塊:用模塊繪製matplotlib

import numpy as np 
import matplotlib.pyplot as plt 

def plotSomething(x,y): 
    fig = plt.figure() 
    ax = fig.add_subplot(111) 
    ax.set_xscale("log", nonposx='clip') 
    ax.set_yscale("log", nonposy='clip') 
    ax.scatter(x,y)         #(1) 
    plt.scatter(x,y)         #(2) 

它繪製得很好,當函數被調用(給定x和y)。 a)如果我註釋掉(1)或(2)只有軸被繪製,但不是散射本身。如果(1)和(2)都未註釋,並且添加變量s = 5,marker ='+'到(1)XOR(2),則該圖將顯示兩個標記(一個在另一個之上) - 默認的「o」和「+」,這意味着我實際上繪製了兩次散點圖。 (1)和(2)取消註釋,我繪製兩次,爲什麼我實際上需要同時具有(1)和(2)才能看到任何分散?爲什麼在(a)我根本沒有散點圖?

我很困惑。任何人都可以指導我?

回答

2

發生了什麼可能與Python的垃圾收集有關。我無法確切地告訴你發生了什麼,因爲提供的代碼示例從不呈現劇情。我猜你正在將它渲染到函數之外,在這種情況下,在渲染(繪製)之前,你實際上正在執行del fig

這應該工作:

def plotSomething(x,y): 
    fig = plt.figure() 
    ax = fig.add_subplot(111) 
    ax.set_xscale("log", nonposx='clip') 
    ax.set_yscale("log", nonposy='clip') 
    ax.scatter(x,y) 
    fig.savefig('test.png') 

如果要延遲渲染/繪製,然後通過一個參考:

def plotSomething(x,y): 
    fig = plt.figure() 
    ax = fig.add_subplot(111) 
    ax.set_xscale("log", nonposx='clip') 
    ax.set_yscale("log", nonposy='clip') 
    ax.scatter(x,y) 
    return fig 
1

(我在對象是如何不同的相互交流不是專家)

您應該添加plt.show(),然後你可以有:(1)或(2)。例如:

#!/usr/bin/python 
import numpy as np 
import matplotlib.pyplot as plt 

def plotSomething(x,y): 
    fig = plt.figure() 
    ax = fig.add_subplot(111) 
    ax.set_xscale("log", nonposx='clip') 
    ax.set_yscale("log", nonposy='clip') 
    #ax.scatter(x,y)         #(1) 
    plt.scatter(x,y)         #(2) 
    plt.show() 

x=[1,2,3] 
y=[5,6,7] 
plotSomething(x,y)