繁体   English   中英

使用matplotlib从模块绘图

[英]plotting with matplotlib from a module

这是我第一次使用python进行绘图,我想我不太了解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),则只会绘制轴的坐标,而不会绘制散点图。

b)但是,如果(1)和(2)都未注释,并且我将var s = 5,marker ='+'添加到(1)XOR(2)中,则该图将同时显示两个标记(一个标记位于其他)-默认的“ o”和“ +”,这意味着我实际上将散点图绘制了两次。

但是-如果同时取消注释(1)和(2),我要绘制两次,为什么实际上我需要同时拥有(1)和(2)才能看到散点图? 为什么在(a)我根本没有散点图的情况下?

我很困惑 谁能指导我?

发生的事情很可能与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

(我不是不同对象之间如何交互的专家)

您应该添加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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM