Raphi Zonis
Raphi Zonis

Reputation: 31

Plotting multiple lines to a single Python figure

This is my first Stack Overflow question so please excuse me if the formatting of this question does not follow the conventions of the Stack Overflow community.

My question is how can you (if possible) add a line to an existing Python figure using pyplot? Essentially, what I want to accomplish is I want to compile and run my code and have that generate a figure with a line on it. Then, what I want to do is change some data in the code, compile and run the code again, and then have the line generated from this running of the code show up on the already existing figure.

fig=plt.figure(figsize=(20,10))
time= np.array(range(0, time_steps+1)) 
sigma_11=Q[:, :, :, 0]
sigma_22=Q[:, :, :, 1]
sigma_12=Q[:, :, :, 2]
vel_x=Q[:, :, :, 3]
vel_y=Q[:, :, :, 4]
stiffness_mat=np.mat([[lamda+2*mu, lamda, 0],
                    [lamda, lamda+2*mu, 0],
                    [0, 0, 2*mu]])

Energ_P=np.zeros((time_steps+1))  
Energ_K=np.zeros((time_steps+1))
Energy_tot=np.zeros((time_steps+1))     
    for n in  range(0, time_steps+1):
Energ_P[n]=(Energy_P(stiffness_mat, Q[:, :, n, 0:3]))
Energ_K[n]=(Energy_K(Q[:, :, n, 3:5]))
Energy_tot[n]=Energ_P[n]+Energ_K[n]

sub1=fig.add_subplot(1, 2, 1)  
sub1.set_title('stress-time')
sub1.plot(time*del_t, sigma_11[bar_cells_x, bar_cells_y, :], label='stress_1')
sub1.plot(time*del_t, sigma_11[bar_cells_x/2, bar_cells_y/2, :], label='stress')
sub1.set_ylabel('sigma_11 [Pa]')
sub1.set_xlabel('time [s]')
sub1.legend(loc='best', fontsize='10')

plt.tight_layout()
plt.show()

I haven't really tried much of anything to solve this yet, save running the code multiple times. However, when I do this, all I end up doing is generating multiple figures.

Upvotes: 1

Views: 732

Answers (1)

lanery
lanery

Reputation: 5364

Try adding the num argument to plt.figure. In other words, replace fig=plt.figure(figsize=(20,10)), with fig=plt.figure(num=1, figsize=(20,10)).

From the docs,

num : integer or string, optional, default: none

If not provided, a new figure will be created, and the figure number will be incremented.

Upvotes: 1

Related Questions