From ee6ad37eb793ed67f71a878cb6acf6ce21a52ddd Mon Sep 17 00:00:00 2001 From: mmcky Date: Wed, 19 Apr 2023 19:52:18 +1000 Subject: [PATCH 1/8] ENH: Set a default image size across all lectures --- lectures/_config.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lectures/_config.yml b/lectures/_config.yml index c1f6e61fc..c6f13baf0 100644 --- a/lectures/_config.yml +++ b/lectures/_config.yml @@ -37,6 +37,9 @@ latex: sphinx: extra_extensions: [sphinx_multitoc_numbering, sphinxext.rediraffe, sphinx_exercise, sphinx_togglebutton, sphinx_proof, sphinx_tojupyter] config: + # myst-nb config + nb_render_image_options: + width: 75% html_favicon: _static/lectures-favicon.ico html_theme: quantecon_book_theme html_static_path: ['_static'] From 91bcb36690969894970ca8aee9e71bc88e8c4e21 Mon Sep 17 00:00:00 2001 From: HengCheng <79777246+2789372130@users.noreply.github.com> Date: Thu, 20 Apr 2023 09:40:21 +1000 Subject: [PATCH 2/8] Remove size settings --- lectures/inequality.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/lectures/inequality.md b/lectures/inequality.md index f1654cc5b..f94283e47 100644 --- a/lectures/inequality.md +++ b/lectures/inequality.md @@ -245,7 +245,6 @@ mystnb: image: alt: lorenz_us classes: shadow bg-primary - width: 75% --- fig, ax = plt.subplots() @@ -313,7 +312,6 @@ mystnb: image: alt: lorenz_gini classes: shadow bg-primary - width: 75% --- fig, ax = plt.subplots() @@ -391,7 +389,6 @@ mystnb: image: alt: gini_simulated classes: shadow bg-primary - width: 75% --- plot_inequality_measures(range(k), ginis, @@ -466,7 +463,6 @@ mystnb: image: alt: gini_wealth_us classes: shadow bg-primary - width: 75% --- xlabel = "year" ylabel = "gini coefficient" @@ -490,7 +486,6 @@ mystnb: image: alt: gini_income_us classes: shadow bg-primary - width: 75% --- xlabel = "year" ylabel = "gini coefficient" @@ -597,7 +592,6 @@ mystnb: image: alt: top_shares_us classes: shadow bg-primary - width: 75% --- xlabel = "year" ylabel = "top $10\%$ share" @@ -678,7 +672,6 @@ mystnb: image: alt: top_shares_simulated classes: shadow bg-primary - width: 75% --- plot_inequality_measures(range(len(topshares)), topshares, @@ -733,7 +726,6 @@ mystnb: image: alt: top_shares_us_al classes: shadow bg-primary - width: 75% --- xlabel = "year" ylabel = "top $10\%$ share" From 8f6be63fa0f9a3598610933c0b656c1796f5270f Mon Sep 17 00:00:00 2001 From: HengCheng <79777246+2789372130@users.noreply.github.com> Date: Thu, 20 Apr 2023 12:46:24 +1000 Subject: [PATCH 3/8] Add global figure setting --- lectures/_config.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/lectures/_config.yml b/lectures/_config.yml index c6f13baf0..5a8c0704b 100644 --- a/lectures/_config.yml +++ b/lectures/_config.yml @@ -40,6 +40,7 @@ sphinx: # myst-nb config nb_render_image_options: width: 75% + classes: shadow bg-primary html_favicon: _static/lectures-favicon.ico html_theme: quantecon_book_theme html_static_path: ['_static'] From 4037bf46ffbe88a7d6893c43dffbf84707435a78 Mon Sep 17 00:00:00 2001 From: HengCheng <79777246+2789372130@users.noreply.github.com> Date: Thu, 20 Apr 2023 15:13:33 +1000 Subject: [PATCH 4/8] Check lecture 1-10 except 6 --- lectures/inequality.md | 8 ---- lectures/supply_demand_heterogeneity.md | 59 +++++++++++++++---------- 2 files changed, 35 insertions(+), 32 deletions(-) diff --git a/lectures/inequality.md b/lectures/inequality.md index f94283e47..b061d11e7 100644 --- a/lectures/inequality.md +++ b/lectures/inequality.md @@ -244,7 +244,6 @@ mystnb: name: lorenz_us image: alt: lorenz_us - classes: shadow bg-primary --- fig, ax = plt.subplots() @@ -311,7 +310,6 @@ mystnb: name: lorenz_gini image: alt: lorenz_gini - classes: shadow bg-primary --- fig, ax = plt.subplots() @@ -388,7 +386,6 @@ mystnb: name: gini_simulated image: alt: gini_simulated - classes: shadow bg-primary --- plot_inequality_measures(range(k), ginis, @@ -462,7 +459,6 @@ mystnb: name: gini_wealth_us image: alt: gini_wealth_us - classes: shadow bg-primary --- xlabel = "year" ylabel = "gini coefficient" @@ -485,7 +481,6 @@ mystnb: name: gini_income_us image: alt: gini_income_us - classes: shadow bg-primary --- xlabel = "year" ylabel = "gini coefficient" @@ -591,7 +586,6 @@ mystnb: name: top_shares_us image: alt: top_shares_us - classes: shadow bg-primary --- xlabel = "year" ylabel = "top $10\%$ share" @@ -671,7 +665,6 @@ mystnb: name: top_shares_simulated image: alt: top_shares_simulated - classes: shadow bg-primary --- plot_inequality_measures(range(len(topshares)), topshares, @@ -725,7 +718,6 @@ mystnb: name: top_shares_us_al image: alt: top_shares_us_al - classes: shadow bg-primary --- xlabel = "year" ylabel = "top $10\%$ share" diff --git a/lectures/supply_demand_heterogeneity.md b/lectures/supply_demand_heterogeneity.md index 508f041b2..019cae4c0 100644 --- a/lectures/supply_demand_heterogeneity.md +++ b/lectures/supply_demand_heterogeneity.md @@ -1,3 +1,14 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + # Market Equilibrium with Heterogeneity @@ -110,7 +121,7 @@ The class will include a test to make sure that $b > > \Pi e $ and raise an ex Now let's proceed to code. -```python +```{code-cell} ipython3 # import some packages import numpy as np import pandas as pd @@ -191,7 +202,7 @@ $$p=\tilde{\mu}^{-1}(\Pi^{\top}b-\Pi^{\top}\Pi e).$$ Thus, we have verified that, up to choice of a numeraire in which to express absolute prices, the price vector in our representative consumer economy is the same as that in an underlying economy with multiple consumers. -```python +```{code-cell} ipython3 class Exchange_economy: def __init__(self, Pi, bs, es, Ws=None, thres=4): """ @@ -262,7 +273,7 @@ class Exchange_economy: -```python +```{code-cell} ipython3 Pi = np.array([[1, 0], [0, 1]]) @@ -281,7 +292,7 @@ print('Competitive equilibrium allocation:', c_s) What happens if the first consumer likes the first good more and the second consumer likes the second good more? -```python +```{code-cell} ipython3 bs = [np.array([6, 5]), # first consumer's bliss points np.array([5, 6])] # second consumer's bliss points @@ -298,7 +309,7 @@ print('Competitive equilibrium allocation:', c_s) Let the first consumer be poorer. -```python +```{code-cell} ipython3 bs = [np.array([5, 5]), # first consumer's bliss points np.array([5, 5])] # second consumer's bliss points @@ -315,7 +326,7 @@ print('Competitive equilibrium allocation:', c_s) Now let's construct an autarky (i.e, no-trade) equilibrium. -```python +```{code-cell} ipython3 bs = [np.array([4, 6]), # first consumer's bliss points np.array([6, 4])] # second consumer's bliss points @@ -332,7 +343,7 @@ print('Competitive equilibrium allocation:', c_s) Now let's redistribute endowments before trade. -```python +```{code-cell} ipython3 bs = [np.array([5, 5]), # first consumer's bliss points np.array([5, 5])] # second consumer's bliss points @@ -352,7 +363,7 @@ print('Competitive equilibrium allocation:', c_s) Now let's use the tricks described above to study a dynamic economy, one with two periods. -```python +```{code-cell} ipython3 beta = 0.95 Pi = np.array([[1, 0], @@ -376,7 +387,7 @@ We use the tricks described above to interpret $c_1, c_2$ as "Arrow securities" -```python +```{code-cell} ipython3 prob = 0.7 Pi = np.array([[np.sqrt(prob), 0], @@ -403,7 +414,7 @@ To compute a competitive equilibrium for a production economy where demand curve Then we compute the equilibrium price vector using the inverse demand or supply curve. -```python +```{code-cell} ipython3 class Production_economy: def __init__(self, Pi, b, h, J, mu): @@ -506,7 +517,7 @@ def plot_competitive_equilibrium(PE): demand_curve = demand_inv(xs) # plot - plt.figure(figsize=[7,5]) + plt.figure() plt.plot(xs, supply_curve, label='Supply', color='#020060') plt.plot(xs, demand_curve, label='Demand', color='#600001') @@ -540,7 +551,7 @@ To do this we * do experiments in which we shift $b$ and watch what happens to $p, c$. -```python +```{code-cell} ipython3 Pi = np.array([[1]]) # the matrix now is a singleton b = np.array([10]) h = np.array([0.5]) @@ -557,7 +568,7 @@ print('Competitive equilibrium allocation:', c.item()) plot_competitive_equilibrium(PE) ``` -```python +```{code-cell} ipython3 c_surplus, p_surplus = PE.compute_surplus() print('Consumer surplus:', c_surplus.item()) @@ -566,7 +577,7 @@ print('Producer surplus:', p_surplus.item()) Let's give consumers a lower welfare weight by raising $\mu$. -```python +```{code-cell} ipython3 PE.mu = 2 c, p = PE.competitive_equilibrium() @@ -577,7 +588,7 @@ print('Competitive equilibrium allocation:', c.item()) plot_competitive_equilibrium(PE) ``` -```python +```{code-cell} ipython3 c_surplus, p_surplus = PE.compute_surplus() print('Consumer surplus:', c_surplus.item()) @@ -586,7 +597,7 @@ print('Producer surplus:', p_surplus.item()) Now we change the bliss point so that the consumer derives more utility from consumption. -```python +```{code-cell} ipython3 PE.mu = 1 PE.b = PE.b * 1.5 c, p = PE.competitive_equilibrium() @@ -607,7 +618,7 @@ This raises both the equilibrium price and quantity. * we can do experiments with a **diagonal** $\Pi$ and also with a **non-diagonal** $\Pi$ matrices to study how cross-slopes affect responses of $p$ and $c$ to various shifts in $b$ -```python +```{code-cell} ipython3 Pi = np.array([[1, 0], [0, 1]]) b = np.array([10, 10]) @@ -624,7 +635,7 @@ print('Competitive equilibrium price:', p) print('Competitive equilibrium allocation:', c) ``` -```python +```{code-cell} ipython3 PE.b = np.array([12, 10]) c, p = PE.competitive_equilibrium() @@ -633,7 +644,7 @@ print('Competitive equilibrium price:', p) print('Competitive equilibrium allocation:', c) ``` -```python +```{code-cell} ipython3 Pi = np.array([[1, 0.5], [0.5, 1]]) b = np.array([10, 10]) @@ -650,7 +661,7 @@ print('Competitive equilibrium price:', p) print('Competitive equilibrium allocation:', c) ``` -```python +```{code-cell} ipython3 PE.b = np.array([12, 10]) c, p = PE.competitive_equilibrium() @@ -689,7 +700,7 @@ The plot indicates that the monopolist's sets output lower than either the comp In a single good case, this equilibrium is associated with a higher price of the good. -```python +```{code-cell} ipython3 def plot_monopoly(PE): """ Plot demand curve, marginal production cost and revenue, surpluses and the @@ -721,7 +732,7 @@ def plot_monopoly(PE): demand_curve = demand_inv(xs) # plot - plt.figure(figsize=[7,5]) + plt.figure() plt.plot(xs, marg_cost_curve, label='Marginal cost', color='#020060') plt.plot(xs, marg_rev_curve, label='Marginal revenue', color='#E55B13') plt.plot(xs, demand_curve, label='Demand', color='#600001') @@ -749,7 +760,7 @@ def plot_monopoly(PE): Let's study compare competitive equilibrium and monopoly outcomes in a multiple goods economy. -```python +```{code-cell} ipython3 Pi = np.array([[1, 0], [0, 1.2]]) b = np.array([10, 10]) @@ -772,7 +783,7 @@ print('Equilibrium with monopolist supplier allocation:', q) #### A single-good example -```python +```{code-cell} ipython3 Pi = np.array([[1]]) # the matrix now is a singleton b = np.array([10]) h = np.array([0.5]) From dd6fe4dada84ee9dd7f25c05d1c8aa077a784e66 Mon Sep 17 00:00:00 2001 From: HengCheng <79777246+2789372130@users.noreply.github.com> Date: Thu, 20 Apr 2023 17:26:56 +1000 Subject: [PATCH 5/8] Check lecture 11-21 --- lectures/cobweb.md | 2 +- lectures/geom_series.md | 80 +++++++++++++++++++++++++++++----------- lectures/olg.md | 17 +++++---- lectures/scalar_dynam.md | 9 ++--- lectures/schelling.md | 5 +-- lectures/solow.md | 11 +++--- 6 files changed, 81 insertions(+), 43 deletions(-) diff --git a/lectures/cobweb.md b/lectures/cobweb.md index dac110bf2..a3f1b70cc 100644 --- a/lectures/cobweb.md +++ b/lectures/cobweb.md @@ -265,7 +265,7 @@ def plot45(model, pmin, pmax, p0, num_arrows=5): """ pgrid = np.linspace(pmin, pmax, 200) - fig, ax = plt.subplots(figsize=(7, 5)) + fig, ax = plt.subplots() ax.set_xlim(pmin, pmax) ax.set_ylim(pmin, pmax) diff --git a/lectures/geom_series.md b/lectures/geom_series.md index 6275f4794..1f54f648d 100644 --- a/lectures/geom_series.md +++ b/lectures/geom_series.md @@ -3,8 +3,10 @@ jupytext: text_representation: extension: .md format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 kernelspec: - display_name: Python 3 + display_name: Python 3 (ipykernel) language: python name: python3 --- @@ -652,7 +654,7 @@ approximations, under different values of $T$, and $g$ and $r$ in Python. First we plot the true finite stream present-value after computing it below -```{code-cell} python3 +```{code-cell} ipython3 # True present value of a finite lease def finite_lease_pv_true(T, g, r, x_0): G = (1 + g) @@ -679,7 +681,13 @@ Now that we have defined our functions, we can plot some outcomes. First we study the quality of our approximations -```{code-cell} python3 +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Finite lease present value $T$ periods ahead" + name: finite_lease_present_value +--- def plot_function(axes, x_vals, func, args): axes.plot(x_vals, func(*args), label=func.__name__) @@ -694,10 +702,9 @@ our_args = (T, g, r, x_0) funcs = [finite_lease_pv_true, finite_lease_pv_approx_1, finite_lease_pv_approx_2] - ## the three functions we want to compare + # the three functions we want to compare fig, ax = plt.subplots() -ax.set_title('Finite Lease Present Value $T$ Periods Ahead') for f in funcs: plot_function(ax, T, f, our_args) ax.legend() @@ -713,12 +720,17 @@ However, holding $g$ and r fixed, our approximations deteriorate as $T$ increase Next we compare the infinite and finite duration lease present values over different lease lengths $T$. -```{code-cell} python3 +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Infinite and finite lease present value $T$ periods ahead" + name: infinite_and_finite_lease_present_value +--- # Convergence of infinite and finite T_max = 1000 T = np.arange(0, T_max+1) fig, ax = plt.subplots() -ax.set_title('Infinite and Finite Lease Present Value $T$ Periods Ahead') f_1 = finite_lease_pv_true(T, g, r, x_0) f_2 = np.full(T_max+1, infinite_lease(g, r, x_0)) ax.plot(T, f_1, label='T-period lease PV') @@ -736,11 +748,16 @@ perpetual lease. Now we consider two different views of what happens as $r$ and $g$ covary -```{code-cell} python3 +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Value of lease of length $T$" + name: value_of_lease +--- # First view # Changing r and g fig, ax = plt.subplots() -ax.set_title('Value of lease of length $T$') ax.set_ylabel('Present Value, $p_0$') ax.set_xlabel('$T$ periods ahead') T_max = 10 @@ -765,9 +782,15 @@ graph. If you aren't enamored of 3-d graphs, feel free to skip the next visualization! -```{code-cell} python3 +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Three period lease PV with varying $g$ and $r$" + name: three_period_lease_PV +--- # Second view -fig = plt.figure() +fig = plt.figure(figsize = [16, 5]) T = 3 ax = plt.subplot(projection='3d') r = np.arange(0.01, 0.99, 0.005) @@ -785,8 +808,7 @@ fig.colorbar(surf, shrink=0.5, aspect=5) ax.set_xlabel('$r$') ax.set_ylabel('$g$') ax.set_zlabel('Present Value, $p_0$') -ax.view_init(20, 10) -ax.set_title('Three Period Lease PV with Varying $g$ and $r$') +ax.view_init(20, 8) plt.show() ``` @@ -803,7 +825,7 @@ represents our present value formula for an infinite lease. After that, we'll use SymPy to compute derivatives -```{code-cell} python3 +```{code-cell} ipython3 # Creates algebraic symbols that can be used in an algebraic expression g, r, x0 = sym.symbols('g, r, x0') G = (1 + g) @@ -814,13 +836,13 @@ print('Our formula is:') p0 ``` -```{code-cell} python3 +```{code-cell} ipython3 print('dp0 / dg is:') dp_dg = sym.diff(p0, g) dp_dg ``` -```{code-cell} python3 +```{code-cell} ipython3 print('dp0 / dr is:') dp_dr = sym.diff(p0, r) dp_dr @@ -839,7 +861,13 @@ We will now go back to the case of the Keynesian multiplier and plot the time path of $y_t$, given that consumption is a constant fraction of national income, and investment is fixed. -```{code-cell} python3 +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Path of aggregate output tver time" + name: path_of_aggregate_output_over_time +--- # Function that calculates a path of y def calculate_y(i, b, g, T, y_init): y = np.zeros(T+1) @@ -857,7 +885,6 @@ y_init = 0 T = 100 fig, ax = plt.subplots() -ax.set_title('Path of Aggregate Output Over Time') ax.set_xlabel('$t$') ax.set_ylabel('$y_t$') ax.plot(np.arange(0, T+1), calculate_y(i_0, b, g_0, T, y_init)) @@ -873,11 +900,16 @@ We now examine what will happen if we vary the so-called **marginal propensity to consume**, i.e., the fraction of income that is consumed -```{code-cell} python3 +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Changing consumption as a fraction of income" + name: changing_consumption_as_fraction_of_income +--- bs = (1/3, 2/3, 5/6, 0.9) fig,ax = plt.subplots() -ax.set_title('Changing Consumption as a Fraction of Income') ax.set_ylabel('$y_t$') ax.set_xlabel('$t$') x = np.arange(0, T+1) @@ -893,7 +925,13 @@ path of output over time. Now we will compare the effects on output of increases in investment and government spending. -```{code-cell} python3 +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Different increase on output" + name: different_increase_on_output +--- fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 10)) fig.subplots_adjust(hspace=0.3) diff --git a/lectures/olg.md b/lectures/olg.md index e3b4b3680..145859cbe 100644 --- a/lectures/olg.md +++ b/lectures/olg.md @@ -561,6 +561,12 @@ plot_ad_as(aggregate_capital_demand, aggregate_supply_capital_crra, m_crra, K_pr Let's plot the aggregate supply with different values of utility parameter $\gamma$ and observe it's behaviour. ```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Aggregate supply" + name: aggregate_supply +--- γ_vals = [0.1, 0.5, 1.5, 2.0] K_prev = 50 @@ -574,7 +580,6 @@ for γ in γ_vals: label=r"$\gamma=$" + str(γ)) ax.set_xlabel("$R_{t+1}$") -ax.set_title("Aggregate Supply") ax.legend() plt.show() ``` @@ -705,7 +710,7 @@ x0 = np.array([0.001, 1.2, 2.6]) def simulate_ts(m, x0_values, ts_length): k_star = optimize.newton(g, 0.2, args=(m,)) - fig, ax = plt.subplots(figsize=(10, 5)) + fig, ax = plt.subplots() ts = np.zeros(ts_length) @@ -797,14 +802,12 @@ def plot_ks_rs(K_t_vals, model): --- mystnb: figure: - caption: 'Equilibrium price and quantity - - ' + caption: "Equilibrium price and quantity" name: equi_ps_q_crra image: alt: equi_ps_q_crra classes: shadow bg-primary - width: 200px + width: 90% --- K_t_vals = np.linspace(0.1, 50, 50) m_crra = create_olg_model(u=crra, u_params={'γ': 0.5}) @@ -900,7 +903,7 @@ def simulate_ts(k0_values, model, ts_length=6): k_star = find_k_star_q(model) print("k_star:", k_star) - fig, ax = plt.subplots(figsize=(10, 5)) + fig, ax = plt.subplots() ts = np.zeros(ts_length) diff --git a/lectures/scalar_dynam.md b/lectures/scalar_dynam.md index cd420c76c..946912e1f 100644 --- a/lectures/scalar_dynam.md +++ b/lectures/scalar_dynam.md @@ -39,7 +39,6 @@ Let's start with some standard imports: ```{code-cell} ipython %matplotlib inline import matplotlib.pyplot as plt -plt.rcParams["figure.figsize"] = (11, 5) #set default figure size import numpy as np ``` @@ -317,9 +316,9 @@ plots. tags: [hide-input, output_scroll] --- -def subplots(fs): +def subplots(): "Custom subplots with axes throught the origin" - fig, ax = plt.subplots(figsize=fs) + fig, ax = plt.subplots() # Set the axes through the origin for spine in ['left', 'bottom']: @@ -335,7 +334,7 @@ def plot45(g, xmin, xmax, x0, num_arrows=6, var='x'): xgrid = np.linspace(xmin, xmax, 200) - fig, ax = subplots((6.5, 6)) + fig, ax = subplots() ax.set_xlim(xmin, xmax) ax.set_ylim(xmin, xmax) @@ -382,7 +381,7 @@ def plot45(g, xmin, xmax, x0, num_arrows=6, var='x'): plt.show() def ts_plot(g, xmin, xmax, x0, ts_length=6, var='x'): - fig, ax = subplots((7, 5.5)) + fig, ax = subplots() ax.set_ylim(xmin, xmax) ax.set_xlabel(r'$t$', fontsize=14) ax.set_ylabel(r'${}_t$'.format(var), fontsize=14) diff --git a/lectures/schelling.md b/lectures/schelling.md index 0c70986c3..c514f5c30 100644 --- a/lectures/schelling.md +++ b/lectures/schelling.md @@ -72,7 +72,6 @@ Let's start with some imports: ```{code-cell} ipython3 %matplotlib inline import matplotlib.pyplot as plt -plt.rcParams["figure.figsize"] = (11, 5) #set default figure size from random import uniform, seed from math import sqrt import numpy as np @@ -246,7 +245,7 @@ def plot_distribution(agents, cycle_num): else: x_values_1.append(x) y_values_1.append(y) - fig, ax = plt.subplots(figsize=(8, 8)) + fig, ax = plt.subplots() plot_args = {'markersize': 8, 'alpha': 0.8} ax.set_facecolor('azure') ax.plot(x_values_0, y_values_0, @@ -429,7 +428,7 @@ def update_agent(i, locations, types): def plot_distribution(locations, types, title, savepdf=False): " Plot the distribution of agents after cycle_num rounds of the loop." - fig, ax = plt.subplots(figsize=(8, 8)) + fig, ax = plt.subplots() colors = 'orange', 'green' for agent_type, color in zip((0, 1), colors): idx = (types == agent_type) diff --git a/lectures/solow.md b/lectures/solow.md index bbcb6e9d5..d214e11c6 100644 --- a/lectures/solow.md +++ b/lectures/solow.md @@ -24,7 +24,6 @@ We will use the following imports ```{code-cell} ipython3 import matplotlib.pyplot as plt -plt.rcParams["figure.figsize"] = (11, 5) #set default figure size import numpy as np ``` @@ -135,7 +134,7 @@ Let's plot the 45 degree diagram of $g$ def plot45(kstar=None): xgrid = np.linspace(xmin, xmax, 12000) - fig, ax = plt.subplots(figsize=(6, 6)) + fig, ax = plt.subplots() ax.set_xlim(xmin, xmax) @@ -233,7 +232,7 @@ ymin, ymax = 0, 3.5 def simulate_ts(x0_values, ts_length): k_star = (s * A / delta)**(1/(1-alpha)) - fig, ax = plt.subplots() + fig, ax = plt.subplots(figsize=[11, 5]) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) @@ -334,7 +333,7 @@ def plot_gcon(kstar=None): k_grid = np.linspace(0, 2.8, 10000) - fig, ax = plt.subplots() + fig, ax = plt.subplots(figsize=[11, 5]) ax.plot(k_grid, g_con(A, s, alpha, delta, k_grid), label='$g(k)$') ax.plot(k_grid, 0 * k_grid, label="$k'=0$") @@ -484,7 +483,7 @@ print(f"Function is maximized at s = {round(s_star_max, 4)}") x_s_max = np.array([s_star_max, s_star_max]) y_s_max = np.array([0, c_star_max]) -fig, ax = plt.subplots() +fig, ax = plt.subplots(figsize=[11, 5]) fps = (c_star_max,) @@ -597,7 +596,7 @@ def k_next(s, alpha, delta, k): ```{code-cell} ipython3 def ts_plot(x_values, ts_length): - fig, ax = plt.subplots() + fig, ax = plt.subplots(figsize=[11, 5]) ts = np.zeros(ts_length) # simulate and plot time series From b9b5f3bda35c89de97d469c51e133108dcf9acaa Mon Sep 17 00:00:00 2001 From: HengCheng <79777246+2789372130@users.noreply.github.com> Date: Thu, 27 Apr 2023 13:45:16 +1000 Subject: [PATCH 6/8] Check all lectures --- lectures/long_run_growth.md | 78 +++++++++++++------------------------ lectures/lp_intro.md | 2 +- lectures/markov_chains_I.md | 7 ++-- lectures/networks.md | 24 ++++++++---- 4 files changed, 48 insertions(+), 63 deletions(-) diff --git a/lectures/long_run_growth.md b/lectures/long_run_growth.md index e31944778..392eb471b 100644 --- a/lectures/long_run_growth.md +++ b/lectures/long_run_growth.md @@ -38,6 +38,7 @@ import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from matplotlib.lines import Line2D +plt.rcParams["figure.figsize"] = (11, 5) #set default figure size ``` +++ {"user_expressions": []} @@ -131,18 +132,23 @@ code_to_name.loc['GBR'] and then using that code to access and plot the data ```{code-cell} ipython3 -fig = plt.figure(dpi=110) +fig = plt.figure() gdppc['GBR'].plot(ax = fig.gca()) ``` We can see that the data is non-continuous for longer periods in early part of this milenium so we could choose to interpolate to get a continuous line plot. ```{code-cell} ipython3 -fig = plt.figure(dpi=110) +--- +mystnb: + figure: + caption: "GDP per Capita (GBR)" + name: gdp_per_capita_gbr +--- +fig = plt.figure() cntry = 'GBR' gdppc[cntry].interpolate().plot( ax = fig.gca(), - title = f'GDP per Capita ({cntry})', ylabel = 'International $\'s', xlabel = 'Year' ); @@ -159,12 +165,17 @@ As you can see from this chart economic growth started in earnest in the 18th Ce How does this compare with other countries growth trajectories? Let's look at the United States (USA), United Kingdom (GBR), and China (CHN) ```{code-cell} ipython3 -fig = plt.figure(dpi=110) +--- +mystnb: + figure: + caption: "GDP per Capita of different countries" + name: gdp_per_capita_diff +--- +fig = plt.figure() ax = fig.gca() cntry = ['USA', 'GBR', 'CHN'] gdppc[cntry].plot( ax = ax, - title = f'GDP per Capita', ylabel = 'International $\'s', xlabel = 'Year' ) @@ -185,7 +196,7 @@ This dataset has been carefully curated to enable cross-country comparisons. Let's compare the growth trajectories of Australia (AUS) and Argentina (ARG) ```{code-cell} ipython3 -fig = plt.figure(dpi=110) +fig = plt.figure() gdppc[['AUS', 'ARG']].plot(ax = fig.gca()) ``` @@ -217,7 +228,7 @@ Gross Domestic Product ```{code-cell} ipython3 cntry = ['DEU', 'SUN', 'USA', 'GBR', 'FRA', 'JPN', 'CHN'] start_year, end_year = (1820,1940) -fig = plt.figure(dpi=110) +fig = plt.figure() gdp[cntry].loc[start_year:end_year].interpolate().plot( ax=fig.gca(), ); @@ -230,7 +241,7 @@ GDP per Capita ```{code-cell} ipython3 cntry = ['DEU', 'SUN', 'USA', 'GBR', 'FRA', 'JPN', 'CHN'] start_year, end_year = (1820,1940) -fig = plt.figure(dpi=110) +fig = plt.figure() gdppc[cntry].loc[start_year:end_year].interpolate().plot( ax=fig.gca() ); @@ -247,9 +258,9 @@ Gross Domestic Product (GDP) ```{code-cell} ipython3 cntry = ['DEU', 'SUN', 'USA', 'GBR', 'FRA', 'JPN', 'CHN'] start_year, end_year = (1970, 2018) -fig = plt.figure(dpi=110) +fig = plt.figure() gdp[cntry].loc[start_year:end_year].interpolate().plot(ax=fig.gca()) -plt.savefig(f"plot-for-tom-gdp-{start_year}-to-{end_year}.png", dpi=200) +plt.savefig(f"plot-for-tom-gdp-{start_year}-to-{end_year}.png") ``` +++ {"user_expressions": []} @@ -259,17 +270,15 @@ GDP per Capita ```{code-cell} ipython3 cntry = ['DEU', 'SUN', 'USA', 'GBR', 'FRA', 'JPN', 'CHN'] start_year, end_year = (1970, 2018) -fig = plt.figure(dpi=110) +fig = plt.figure() gdppc[cntry].loc[start_year:end_year].interpolate().plot( ax=fig.gca() ); ``` - +++ {"user_expressions": []} - --- ## Other Interesting Plots @@ -279,7 +288,7 @@ Here are a collection of interesting plots that could be linked to interesting s Looking at China GDP per capita levels from 1500 through to the 1970's showed a long period of declining GDP per capital levels from 1700's to early 20th century. (Closed Border / Inward Looking Domestic Focused Policies?) ```{code-cell} ipython3 -fig = plt.figure(dpi=110) +fig = plt.figure() gdppc['CHN'].loc[1500:1980].interpolate().plot(ax=fig.gca()); ``` @@ -288,13 +297,10 @@ gdppc['CHN'].loc[1500:1980].interpolate().plot(ax=fig.gca()); China (CHN) then followed a very similar growth story from the 1980s through to current day China. ```{code-cell} ipython3 -fig = plt.figure(dpi=110) +fig = plt.figure() gdppc[['CHN', 'GBR']].interpolate().plot(ax = fig.gca()) ``` -```{code-cell} ipython3 - -``` +++ {"user_expressions": []} @@ -319,7 +325,7 @@ worldgdppc = regionalgdppc['World GDP pc'] ``` ```{code-cell} ipython3 -fig = plt.figure(dpi=110) +fig = plt.figure() ax = worldgdppc.plot( ax = fig.gca(), title='World GDP per capita', @@ -329,44 +335,17 @@ ax = worldgdppc.plot( ``` ```{code-cell} ipython3 -fig = plt.figure(dpi=110) +fig = plt.figure() regionalgdppc[['Western Offshoots', 'Sub-Sahara Africa']].plot(ax = fig.gca()) ``` ```{code-cell} ipython3 -fig = plt.figure(dpi=200) +fig = plt.figure() line_styles = ['-', '--', ':', '-.', '.', 'o'] # TODO: Improve this ax = regionalgdppc.plot(ax = fig.gca(), style=line_styles) plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5)) ``` -```{code-cell} ipython3 - -``` - -```{code-cell} ipython3 - -``` - -```{code-cell} ipython3 - -``` - -```{code-cell} ipython3 - -``` - -```{code-cell} ipython3 - -``` - -```{code-cell} ipython3 - -``` - -```{code-cell} ipython3 - -``` +++ {"user_expressions": []} @@ -504,6 +483,3 @@ wbiall = wbi.drop(['Country Name' , 'Indicator Name', 'Indicator Code'], axis=1) get_log_hist(wbiall, ['1960', '1990', '2020']) ``` -```{code-cell} ipython3 - -``` diff --git a/lectures/lp_intro.md b/lectures/lp_intro.md index f9196b4c2..36fd6574a 100644 --- a/lectures/lp_intro.md +++ b/lectures/lp_intro.md @@ -99,7 +99,7 @@ The following graph illustrates the firm's constraints and iso-revenue lines. --- tags: [hide-input] --- -fig, ax = plt.subplots(figsize=(8, 6)) +fig, ax = plt.subplots() ax.grid() # Draw constraint lines diff --git a/lectures/markov_chains_I.md b/lectures/markov_chains_I.md index f10596a41..702c0d6e1 100644 --- a/lectures/markov_chains_I.md +++ b/lectures/markov_chains_I.md @@ -57,7 +57,6 @@ Let's start with some standard imports: ```{code-cell} ipython3 import matplotlib.pyplot as plt -plt.rcParams["figure.figsize"] = (11, 5) # set default figure size import quantecon as qe import numpy as np from graphviz import Digraph @@ -559,7 +558,7 @@ To answer this, we let $\psi_t$ be the distribution of $X_t$ for $t = 0, 1, 2, \ Our first aim is to find $\psi_{t + 1}$ given $\psi_t$ and $P$. -To begin, pick any $y \in S$. +To begin, pick any $y \in S$. To get the probability of being at $y$ tomorrow (at $t+1$), we account for all ways this can happen and sum their probabilities. @@ -857,7 +856,7 @@ Now we plot the sequence ```{code-cell} ipython3 ψ_0 = (0.0, 0.2, 0.8) # Initial condition -fig = plt.figure(figsize=(8, 6)) +fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set(xlim=(0, 1), ylim=(0, 1), zlim=(0, 1), @@ -920,7 +919,7 @@ def plot_distribution(P, ts_length, num_distributions): ψ_star = mc.stationary_distributions[0] ## Draw the plot - fig, axes = plt.subplots(nrows=1, ncols=n) + fig, axes = plt.subplots(nrows=1, ncols=n, figsize=[11, 5]) plt.subplots_adjust(wspace=0.35) ψ_0s = generate_initial_values(num_distributions) diff --git a/lectures/networks.md b/lectures/networks.md index eb0de92bf..1d841aea4 100644 --- a/lectures/networks.md +++ b/lectures/networks.md @@ -432,7 +432,7 @@ however in {numref}`poverty_trap_2` rich is not accessible from poor, thus it is We can verify this by first constructing the graphs using Networkx and then using `nx.is_strongly_connected`. ```{code-cell} ipython3 -fig, ax = plt.subplots(figsize = (5,5)) +fig, ax = plt.subplots() G1 = nx.DiGraph() G1.add_edges_from([('p', 'p'),('p','m'),('p','r'), @@ -447,7 +447,7 @@ nx.is_strongly_connected(G1) #checking if above graph is strongly connected ``` ```{code-cell} ipython3 -fig, ax = plt.subplots(figsize = (5,5)) +fig, ax = plt.subplots() G2 = nx.DiGraph() G2.add_edges_from([('p', 'p'), @@ -507,7 +507,7 @@ edge_colors = [] for src,_ in G.edges: edge_colors.append(node_to_color[src]) -fig, ax = plt.subplots(figsize=(8, 10)) +fig, ax = plt.subplots(figsize=(10, 10)) ax.axis('off') nx.draw_networkx_nodes(G, @@ -592,7 +592,6 @@ mystnb: image: alt: poverty_trap_weighted classes: shadow bg-primary - width: 500px tags: [hide-input] --- graph3 = graphviz.Digraph(comment='Graph') @@ -960,7 +959,6 @@ mystnb: image: alt: sample_gph_1 classes: shadow bg-primary - width: 500px --- G7 = nx.DiGraph() @@ -1156,13 +1154,19 @@ eig_central = eigenvector_centrality(Z) ``` ```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Eigenvector centrality" + name: eigenvector_centrality +--- fig, ax = plt.subplots() df = centrality_plot_data(countries, eig_central) ax.bar('code', 'centrality', data=df, color=df["color"], alpha=0.6) -patch = mpatches.Patch(color=None, label='eigenvector centrality', visible=False) +patch = mpatches.Patch(color=None, visible=False) ax.legend(handles=[patch], fontsize=12, loc="upper left", handlelength=0, frameon=False) plt.show() @@ -1291,13 +1295,19 @@ ecentral_authority = eigenvector_centrality(Z, authority=True) ``` ```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Eigenvector authority" + name: eigenvector_centrality +--- fig, ax = plt.subplots() df = centrality_plot_data(countries, ecentral_authority) ax.bar('code', 'centrality', data=df, color=df["color"], alpha=0.6) -patch = mpatches.Patch(color=None, label='eigenvector authority', visible=False) +patch = mpatches.Patch(color=None, visible=False) ax.legend(handles=[patch], fontsize=12, loc="upper left", handlelength=0, frameon=False) plt.show() From 771cef1d74c1a8e720d5a0f14ef77ac20617481c Mon Sep 17 00:00:00 2001 From: HengCheng <79777246+2789372130@users.noreply.github.com> Date: Thu, 27 Apr 2023 13:57:52 +1000 Subject: [PATCH 7/8] Remove unnessesary settings --- lectures/networks.md | 24 +----------------------- 1 file changed, 1 insertion(+), 23 deletions(-) diff --git a/lectures/networks.md b/lectures/networks.md index 1d841aea4..f27117e8a 100644 --- a/lectures/networks.md +++ b/lectures/networks.md @@ -97,10 +97,6 @@ mystnb: figure: caption: "Commercial Aircraft Network \n" name: aircraft_network - image: - alt: aircraft_network - classes: shadow bg-primary - width: 500px tags: [hide-input] --- ch1_data = qbn_data.introduction() @@ -268,10 +264,6 @@ mystnb: figure: caption: "Poverty Trap 1 \n" name: poverty_trap_1 - image: - alt: poverty_trap_1 - classes: shadow bg-primary - width: 500px --- graph1 = graphviz.Digraph(comment='Graph',engine = "neato") graph1.attr(rankdir='LR') @@ -299,10 +291,6 @@ mystnb: figure: caption: "Poverty Trap \n" name: poverty_trap_2 - image: - alt: poverty_trap_2 - classes: shadow bg-primary - width: 500px --- graph2 = graphviz.Digraph(comment='Graph',engine="neato") graph2.attr(rankdir='LR') @@ -479,10 +467,6 @@ mystnb: figure: caption: "International Credit Network \n" name: financial_network - image: - alt: financial_network - classes: shadow bg-primary - width: 500px tags: [hide-input] --- Z = ch1_data["adjacency_matrix_2019"]["Z"] @@ -589,9 +573,6 @@ mystnb: figure: caption: "Weighted Poverty Trap \n" name: poverty_trap_weighted - image: - alt: poverty_trap_weighted - classes: shadow bg-primary tags: [hide-input] --- graph3 = graphviz.Digraph(comment='Graph') @@ -956,9 +937,6 @@ mystnb: figure: caption: Sample Graph name: sample_gph_1 - image: - alt: sample_gph_1 - classes: shadow bg-primary --- G7 = nx.DiGraph() @@ -1158,7 +1136,7 @@ eig_central = eigenvector_centrality(Z) mystnb: figure: caption: "Eigenvector centrality" - name: eigenvector_centrality + name: eigenvctr_centrality --- fig, ax = plt.subplots() From c9a5cc06b09d4b31e6aa980574e1a5c558dbf233 Mon Sep 17 00:00:00 2001 From: HengCheng <79777246+2789372130@users.noreply.github.com> Date: Fri, 28 Apr 2023 10:33:07 +1000 Subject: [PATCH 8/8] Update width and remove shadow --- lectures/_config.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lectures/_config.yml b/lectures/_config.yml index 5a8c0704b..8e94ffe44 100644 --- a/lectures/_config.yml +++ b/lectures/_config.yml @@ -39,8 +39,7 @@ sphinx: config: # myst-nb config nb_render_image_options: - width: 75% - classes: shadow bg-primary + width: 80% html_favicon: _static/lectures-favicon.ico html_theme: quantecon_book_theme html_static_path: ['_static']