简体   繁体   中英

plotting with matplotlib from a module

It's the first time I'm using python to plot and I guess I don't quite understand the interactions between objects in matplotlib. I'm having the following module:

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)

and it plots just fine when the function is called (given x and y).

a) If I comment out (1) or (2) only the axis' get plotted but not the scatter itself.

b) However, if both (1) and (2) are uncommented and I add the vars s=5, marker='+' to either (1) XOR (2) the the figure will show both markers (one on top of the other) - the default 'o' and the '+', meaning that I actually plot the scatter twice.

BUT - if by having both (1) and (2) uncommented I'm plotting twice, why do I actually need to have both (1) and (2) in order to see any scatter? why in case (a) I get no scatter plot at all?

I'm puzzled. Can anyone guide me through?

What is happening is likely related to Python's garbage collection. I can't tell you exactly what is going on because the provided code sample never renders the plot. I'm guessing that you are rendering it outside the function, in which case, you are effectively doing a del fig before rendering (drawing).

This should work:

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')

If you want to delay the render/draw then pass a reference:

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

(I'm no expert in how different objects interact with each other)

You should add plt.show() and then you can have either (1) or (2). For example:

#!/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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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