记录一下在jupyter notebook中使用plt.show()的注意事项

记录一下在jupyter notebook中使用plt.show()的注意事项

在jupyter notebook中使用matplotlib画图时,发现plt.show()总是不显示画出来的图,代码如下

import numpy as np
# import matplotlib
# matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
%matplotlib inline

stars=np.array([[12660,2716,1426,945,1192],[667,300,134,112,402],[6704,2096,999,639,1032]])
fig = plt.figure(num=1,figsize=(10,5)) # 定义画布
ax = fig.add_subplot(111) # 在fig上放一个ax
scale=20000
stars=np.array([[12660,2716,1426,945,1192],[667,300,134,112,402],[6704,2096,999,639,1032]])

stars_sum=np.sum(stars,1)
stars_sum.resize((3,1))
stars=stars/stars_sum*scale

category_colors = plt.get_cmap('BuGn')(
        np.linspace(0.85, 0.2, stars.shape[1]))#获取颜色 ,从色谱中拿色

init =[0,0,0]

#%%
for i,color in enumerate(category_colors):
    ax.barh(y=np.linspace(1,3,num=3),width=stars[:,i],left=init,color=color)
    init = init + stars[:,i]

ax.barh(y=np.linspace(1,3,num=3),width=stars[:,0],left=init,color=category_colors[0])
plt.show() # 注意这里是不会显示图的,因为plt.show是阻塞的,不把上一个图关了就不能显示出来新的图,只能用下面的fig
#%%
fig

在jupyter notebook中是这样的
在这里插入图片描述

这里画的是什么都不用管,#%%代表一个cell,所以这里一共三个cell。
发现运行前两个cell以后,在plt.show()下面没有打印出图片。
查了很久,最后看了一下plt.show()的源码说明,都明白了,原来第一个cell定义ax的时候自己就画了一个空白的,
plt.show()的画图是阻塞的,不把这个空白的关了就不能画新的,也就是说只能有一个ax对应的图存在~~(别问我咋关,我不会)~~

def show(*args, **kw):
    """
    Display a figure.
    When running in ipython with its pylab mode, display all
    figures and return to the ipython prompt.

    In non-interactive mode, display all figures and block until
    the figures have been closed; in interactive mode it has no
    effect unless figures were created prior to a change from
    non-interactive to interactive mode (not recommended).  In
    that case it displays the figures but does not block.

    A single experimental keyword argument, *block*, may be
    set to True or False to override the blocking behavior
    described above.
    """

这也就解释了如果把第一个和第二个cell放在一起,是能够画出来的。

下面划重点

那么,以后在jupyter notebook中要查看画的图的时候,要用第三个cell的方法,直接输入fig就可以查看了。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值