0

I use IPython/Matplotlib, and I want to create functions that can plot various graphs in the same plotting window. However, I have trouble with redrawing. This is my program test_plot_simple.py:

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y2 = (x**2)/(10**2)
ye = (2**x)/(2**10)
fig, ax = plt.subplots()

def p_squared():
    ax.plot(x,y2, 'r')
    plt.show()

def p_exp():
    ax.plot(x,ye, 'r')
    plt.show()

I start IPython as $ python --matplotlib

On the IPython command line I do

In [1]: run test_plot_simple.py
In [2]: p_squared()
In [3]: p_exp()

After the second line, the squared graph is shown. But nothing happens after the second. Why is the plt.show() not working here?

2 Answers 2

1

It appears as though you call subplots without actually taking advantage of them, namely that you are trying to over plot on the same canvas. See here for a more thorough explanation. That being said, all you need is the following in order to have the functionality I think you want:

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y2 = (x**2)/(10**2)
ye = (2**x)/(2**10)

def p_squared():
    plt.plot(x,y2, 'r')
    plt.show()

def p_exp():
    plt.plot(x,ye, 'r')
    plt.show()

Now both the p_squared() and p_exp() calls produce plots. Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

This helps in the simple example. However, for other reasons I need to go with an object-oriented approach where I can keep track of the axis from the very start. Thus I do indeed need to do the plotting via ax.plot().
0

After some digging I think I found the right way to go about this. It seems that show() is not really intended for this purpose, but rather draw() is. And if I want to keep it object-oriented, I should draw via my figure or my axis. It seems to me that something like this is the best approach:

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y2 = (x**2)/(10**2)
ye = (2**x)/(2**10)
fig, ax = plt.subplots()
fig.show()

def p_squared():
    ax.plot(x,y2, 'r')
    fig.canvas.draw()

def p_exp():
    ax.plot(x,ye, 'r')
    fig.canvas.draw()

I.e., use fig.canvas.draw() in lieu of plt.show() (or fig.show(), for that matter.)

I still need one show() - I chose to do that right away after the figure has been created.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.