QuantEcon / lecture-python-intro

An Undergraduate Lecture Series for the Foundations of Computational Economics
https://intro.quantecon.org/
39 stars 20 forks source link

[cobweb] Animation for naive expectation #533

Open longye-tian opened 2 months ago

longye-tian commented 2 months ago

Dear John @jstac and Matt @mmcky ,

When I went through the issues last week, I found #79, which is related to animating the dynamics of the cobweb model.

I propose to use the following code to animate the naive expectation with persistent cycles.

We need these two extra imports

from matplotlib.animation import FuncAnimation
from IPython.display import HTML

and replace plot45() by the following code:

fig, ax = plt.subplots(figsize=(9, 8))
ax.set_xlabel('$p_t$')
ax.set_ylabel('$p_{t+1}$')

ax.plot([0, 9], [0, 9],lw=1, alpha=0.7, label='45°')

p_grid = np.linspace(0, 9, 200)
ax.plot(p_grid, [g(m, p) for p in p_grid], 'b-',lw=2, alpha=0.6, label='g')

ax.legend()

cobweb, = ax.plot([], [], lw=1.5)
point, = ax.plot([], [], '.', markersize=20)

def animate(i):
    p0 = 2 
    x, y = [p0], [p0]
    p = p0

    for _ in range(i):
        p_next = g(m, p)
        x.extend([p, p])
        y.extend([p_next, p_next])
        x.append(p_next)
        y.append(p_next)
        p = p_next

    cobweb.set_data(x, y)
    point.set_data([p], [p])
    return cobweb, point

anim = FuncAnimation(fig, animate, frames=20, interval=500, blit=True)
plt.close()
HTML(anim.to_jshtml())

Here is the animation generated by the code:

https://github.com/user-attachments/assets/4696a793-2aa4-49c5-8faa-4460d29ae5b1

For your reference, I attached the current plot as follows:

naive

What do you think about this change? Would you like to change anything?

Best ❤️ Longye

mmcky commented 2 months ago

thanks @longye-tian. I really like the animations -- but I also really like the static representation here. I think it maybe useful to have both. Would it be possible to have them side-by-side do you think?

longye-tian commented 2 months ago

thanks @longye-tian. I really like the animations -- but I also really like the static representation here. I think it maybe useful to have both. Would it be possible to have them side-by-side do you think?

Hi Matt @mmcky,

Yes, if we delete the following code in the animation code, we will have a static version following the animation

plt.close()

The only issue is that the static version does not look like the original plot. Here is the static version looks like

static

Another way is to keep the original code for the static plot and add the animation separately.

Best, Longye

mmcky commented 2 months ago

@longye-tian I wonder if we can introduce tabs (from sphinx-design) to show a static and dynamic version.

https://sphinx-design.readthedocs.io/en/latest/tabs.html

I will need to think about pdflatex compatibility but it would be nice way to show both.