Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse and plot more than once the same plot

Using matplotlib, on Jupyter books, I want to make a figure with some plots, show it, add more plots, and show it again (old and new plots)

instead, it shows me only new plots on the new second image

This is the code I have:

import numpy as np
%matplotlib inline  
import matplotlib.pyplot as plt

a=np.random.rand(10,)
b=np.random.rand(10,)

fig1 = plt.figure(1)
plt.plot(a,'b')
#plt.draw();
plt.show();

plt.figure(1)
plt.plot(b,'g--')
plt.show();

left is what I have, right is what I want :

enter image description here


The question upside has been reduced to the most simplistic form, therefore I may have not explain that I do not want to having to recreate the figure each time (as it has about 15 lines to configure as I desire)

This is an example of code I DO NOT want:

import numpy as np
%matplotlib inline  
import matplotlib.pyplot as plt

a=np.random.rand(10,)
b=np.random.rand(10,)
c=np.random.rand(10,)

plt.plot(a, 'b')
plt.grid(True)

dig, ax = plt.subplots(1)
ax.plot(a,'b')
ax.plot(b,'g--')

dig, bx = plt.subplots(1)
bx.plot(a,'b')
bx.plot(b,'g--')
bx.plot(c,'r.')

plt.show()

this is a sort of pseudocode I would expect:

a=np.random.rand(10,)
b=np.random.rand(10,)
c=np.random.rand(10,)

my_plot = plt.figure()
my_plot.grid(True)

my_plot.addplot(a,'b')
my_plot.show()

my_plot.addplot(a,'g--')
my_plot.show()

my_plot.addplot(a,'r.')
my_plot.show()

(I know, this is not phyton/matplotlib, but I am sure something elegant like this should be possible)

like image 933
widot Avatar asked Sep 18 '25 23:09

widot


1 Answers

import numpy as np
%matplotlib inline  
import matplotlib.pyplot as plt

a=np.random.rand(10,)
b=np.random.rand(10,)
c=np.random.rand(10,)
d=np.random.rand(10,)

p = [a,b,c,d]
colors = ['r','g','b', 'g--']
for i in range(len(p)):
    fig, ax = plt.subplots(1)
    for j in range(i + 1):
        ax.plot(p[j], colors[j])

plot

like image 143
vb_rises Avatar answered Sep 20 '25 13:09

vb_rises