aloctavodia / BAP3

Figures and code examples from Bayesian Analysis with Python (third edition)
http://bap.com.ar/
142 stars 41 forks source link

chap_01.ipynb warning "Possibly did not call parent GridSpec with the "figure" keyword" #7

Closed whoispo closed 7 months ago

whoispo commented 7 months ago

When I run the cell content as

x, y = np.mgrid[-4:4:.01, -4:4:.01]
pos = np.empty(x.shape + (2,))
pos[:, :, 0] = x; pos[:, :, 1] = y
rv = pz.MvNormal([0, 0], [[1, 0.8], 
                          [0.8, 1]])

x_value = pos[:, :, 0][:,0]
x_density = rv.pdf(pos)

left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left + width + 0.02

rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]

plt.figure(1, figsize=(8, 8))

ax_joint = plt.axes(rect_scatter)
ax_x = plt.axes(rect_histx)
ax_y = plt.axes(rect_histy)

ax_joint.imshow(x_density, cmap='cet_gray_r', origin='lower', extent=[-3, 3, -3, 3])

ax_joint.plot(x_value, x_density[400]*2, 'k:', lw=2)
ax_joint.plot(x_value, x_density[500]*2+1, 'k:', lw=2)
ax_joint.plot(x_value, x_density[300]*2-1, 'k:', lw=2)

ax_x.fill_between(x_value, x_density.sum(1), color='C2')
ax_y.fill_betweenx(x_value, x_density.sum(1), color='C2')

for ax in [ax_joint, ax_x, ax_y]:
    ax.grid(False)
    ax.set_facecolor('w')
    ax.set_xticks([])
    ax.set_yticks([])
ax_joint.set_xlim(-3, 3)
ax_joint.set_ylim(-3, 3)
ax_x.set_xlim(-3, 3)
ax_y.set_ylim(-3, 3)
ax_x.set_xlim(-3, 3)
ax_joint.set_ylabel('$B$', rotation=0, labelpad=20, fontsize=18)
ax_joint.set_xlabel('$A$', fontsize=18)

ax_joint.text(-2.5, 2.5, '$p(A, B)$', fontsize=18, color='k', weight='medium')
ax_y.text(10, 0, '$p(B)$', fontsize=18, color='k', weight='medium')
ax_x.text(-0.2, 15, '$p(A)$', fontsize=18, color='k', weight='medium')
ax_joint.text(1, -2, ' ... $p(A \mid B)$', fontsize=18, color='k', weight='medium')
plt.savefig('../fig/joint_marginal_cond.png')

jupyter issue 2 warnings

/tmp/ipykernel_5463/4085251966.py:52: UserWarning: There are no gridspecs with layoutgrids. Possibly did not call parent GridSpec with the "figure" keyword plt.savefig('../fig/joint_marginal_cond.png') /home/osvaldo/anaconda3/envs/bap3/lib/python3.11/site-packages/IPython/core/pylabtools.py:152: UserWarning: There are no gridspecs with layoutgrids. Possibly did not call parent GridSpec with the "figure" keyword fig.canvas.print_figure(bytes_io, **kw)

I looked up the matplot API and found if I changed

plt.figure(1, figsize=(8, 8))

ax_joint = plt.axes(rect_scatter)
ax_x = plt.axes(rect_histx)
ax_y = plt.axes(rect_histy)`

to

_, axes_arr = plt.subplots(1, 3, figsize=(8, 8))
ax_joint, ax_x, ax_y = axes_arr
ax_joint.set_position(rect_scatter)
ax_x.set_position(rect_histx)
ax_y.set_position(rect_histy)

The warning problems can be fixed.

aloctavodia commented 7 months ago

Thanks! I have updated the notebook