记录一下在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
就可以查看了。