Python equivalent to 'hold on' in Matlab

PythonMatlabGraphMatplotlib

Python Problem Overview


Is there an explicit equivalent command in Python's matplotlib for Matlab's hold on? I'm trying to plot all my graphs on the same axes. Some graphs are generated inside a for loop, and these are plotted separately from su and sl:

import numpy as np
import matplotlib.pyplot as plt

for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)
    plt.axis([0,50,60,80])

plt.show()

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.axis([0,50,60,80])
plt.show()

Python Solutions


Solution 1 - Python

Just call plt.show() at the end:

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0,50,60,80])
for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)    

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.show()

Solution 2 - Python

You can use the following:

plt.hold(True)

Solution 3 - Python

The hold on feature is switched on by default in matplotlib.pyplot. So each time you evoke plt.plot() before plt.show() a drawing is added to the plot. Launching plt.plot() after the function plt.show() leads to redrawing the whole picture.

Solution 4 - Python

check pyplot docs. For completeness,

import numpy as np
import matplotlib.pyplot as plt

#evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

Solution 5 - Python

Use plt.sca(ax) to set the current axes, where ax is the Axes object you'd like to become active.

For example:

In a first function: import numpy as np import matplotlib.pyplot as plt

for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)
    plt.axis([0,50,60,80])

plt.show()

In the next function: def function2(...., ax=None)

if ax is None:
    fig, ax = plt.subplots(1)
else:
    plt.sca(ax)

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.axis([0,50,60,80])
plt.show()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMedulla OblongataView Question on Stackoverflow
Solution 1 - PythonAlvaro FuentesView Answer on Stackoverflow
Solution 2 - PythonmapsaView Answer on Stackoverflow
Solution 3 - PythonfreudeView Answer on Stackoverflow
Solution 4 - PythonCKMView Answer on Stackoverflow
Solution 5 - PythonBen van OeverenView Answer on Stackoverflow