2011-02-23 93 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)