'Update plot in a loop in Jupyter Notebook
I am making multiple plots on the same canvas using data from dataframe. I want to update the plot in a loop based on newly filtered data.
The code I am using is:
from IPython import display
fig = plt.figure(figsize = (10,13))
ax.set_xlim(-0.5,2.5)
ax.set_ylim(-0.5,3.5)
# d_a is a list of dataframes created using different filters
for data_filtered in d_a:
for index,row in data_filtered.iterrows():
x_values = [row['x'] - xy_offset[row['direction']][0]/2.1,
row['x']+xy_offset[row['direction']][0]/2.1]
y_values = [row['y']-xy_offset[row['direction']][1]/2.1,
row['y']+xy_offset[row['direction']][1]/2.1]
# for each row in the dataframe a plot is drawn
plt.plot(x_values,y_values, linewidth=20,color= 'green',
alpha = 0.1
)
t.sleep(0.5)
display.display(plt.gcf())
display.clear_output(wait =True)
Output:(Dynamic and changes with the iteration)

Now the idea is to use a varying value of 'alpha' in the plot based on a certain value in the row of the dataframe. When I plot this, the opacity just keeps on increasing even when alpha is kept constant as in the code snipped shown.
Shouldn't the display be cleared entirely and a new plot made instead?
Solution 1:[1]
You need to clear either the matplotlib axis or figure also, with plt.cla() or plt.clf() respectively. Otherwise the lines will be drawn onto the same matplotlib axis object in memory, and redrawn at each iteration.
from IPython import display
import numpy as np
import time as t
fig = plt.figure(figsize = (10,13))
ax = fig.subplots()
shifts = [1, 3, 4, 1, 2, 5, 2]
for shift in shifts:
ax.plot([0, 1], [0 + shift/10, 1 - shift/10], linewidth=20, color= 'green', alpha = 0.1)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
display.display(plt.gcf())
t.sleep(0.5)
plt.cla()
display.clear_output(wait =True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fokkerplanck |
