Question

I have two similar pieces of matplotlib codes that produce different results.

1:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,10,100)
y = np.linspace(0,10,100)
y[10:40] = np.nan
plt.plot(x,y)
plt.savefig('fig')

2:

from pylab import *

x = linspace(0,10,100)
y = linspace(0,10,100)
y[10:40] = np.nan
plot(x,y)
savefig('fig')

Code #1 produces a straight line with the NaN region filled in with a solid line of a different color

Code #2 produces a figure with a straight line but does not fill in the NaN region with a line. Instead there is a gap there.

How can I make code # 1 produce a gap in place of NaN's like code #2. I have been googling for a couple of days and have come up with nothing. Any help or advice would be appreciated. Thanks in advance

Was it helpful?

Solution

Just to explain what's probably happening:

The two pieces of code you showed are identical. They will always produce the same output if called by themselves. pylab is basically a just a few lines of code that does: (There's a bit more to it than this, but it's the basic idea.)

from numpy import *
from matplotlib.mlab import *
from matplotlib.pyplot import *

There's absolutely no way for pylab.plot to reference a different function than plt.plot


However, if you just call plt.plot (or pylab.plot, they're the same function), it plots on the current figure.

If you plotted something on that figure before, it will still be there. (If you're familiar with matlab, matplotlib defaults to hold('on'). You can change this with plt.hold, but it's best to be more explicit in python and just create a new figure.)

Basically, you probably did this:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,10,100)
y = np.linspace(0,10,100)

plt.plot(x,y)
plt.savefig('fig')

And then, in the same interactive ipython session, you did this:

y[10:40] = np.nan
plt.plot(x, y)
plt.savefig('fig')

Because you didn't call show, the current figure is still the same one as it was before. The "full" line is still present beneath the second one, and the second line with the NaN's is a different color because you've plotted on the same axes.

This is one of the many reasons why it's a good idea to use the object-oriented interface. That way you're aware of exactly which axes and figure you're plotting on.

For example:

fig, ax = plt.subplots()
ax.plot(x, y)
fig.savefig('test.png')

If you're not going to do that, at very least always explicitly create a new figure and/or axes when you want a new figure. (e.g. start by calling plt.figure())

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top