关于python idle不能成功运行matplotlib中函数的解答

前言

我一般在spyder上运行python程序,但是启动spyder常常比较费时间。所以有时候为了方便我会用python自带的idle来写程序,运行程序。今天在使用matplotlib中的plot函数和bar函数的时候,发现在idle里面根本没法出画图结果,在此记录我解决自己疑惑的过程。

问题描述

在这里插入图片描述

即:我在python idle中输入:

from matplotlib.pyplot import *

a=[1,2,3]
b=[2,4,6]
bar(a,b)

或者

from matplotlib.pyplot import *

a=[1,2,3]
b=[2,4,6]
bar(a,b)
show()

结果都如上图左侧所示,shell没有出任何结果。

但是在spyder中运行同样的代码,结果如下:

在这里插入图片描述

原因分析

1)失败尝试

首先,我找到了这个网页 [1],里面说:

The problem is probably due to a conflict between idle and the matplotlib backend. Instead of using idle, try using ipython, which is included in the superpack, and start ipython in the pylab mode, i.e., run ipython -pylab at the command line.

抑或

Just use import pylab pylab.show() this will display the graph in separate window.

但是我发现都没用。唯一让我感到收获的是那一句:probably due to a conflict between idle and the matplotlib backend,但是并没有讲到根本。

2)正确尝试

于是,通过一番搜索(Google),认真选定关键词,最后我找到了 [2]
Gui shells are at best problematic, because they have to run a mainloop, but interactive plotting also involves a mainloop. Ipython has sorted all this out for the primary matplotlib backends. There may be other shells and IDEs that also work with matplotlib in interactive mode, but one obvious candidate does not: the python IDLE IDE is a Tkinter gui app that does not support pylab interactive mode, regardless of backend.

意思就是:python自带的IDLE是一个Tkiner GUI app,Tkiner需要运行一个主循环,然而matplotlib(interactive plotting交互式画图)也会运行一个主循环。这样一来二者就会冲突卡死。所以IDLE不支持pylab和matplotlib。

终于破案。

3)解决方案

就是不要在IDLE中运行matplotlib中的画图函数。

可以转用pycharm或者spyder或者ipython等等。

4)补充知识

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html 给出了很多matplotlib内置的函数,我觉得还是很有参考价值的(可以作为一个handbook来用),所以在这里点出来。

补充问题:如何在matplotlib作图中显示中文

1)问题描述

此外,我还发现,在matplotlib中不会自动显示中文,比如在spyder中运行:

from matplotlib.pyplot import *
a=[1,2,3]
b=[2,4,6]
xlabels=['one呵呵','two呵呵','three呵呵']
xticks(range(1,len(xlabels)+1),xlabels,rotation=45)
bar(a,b,color='k')
show()

结果是:
在这里插入图片描述

可以看到,中文并没有显示出来,而是变成了空白的方框****。

2)解决方案

修改代码,即加入两行:

from matplotlib.pyplot import *
from pylab import *   									# 新加的代码1
mpl.rcParams['font.sans-serif']=['KaiTi']	            # 新加的代码2
a=[1,2,3]
b=[2,4,6]
xlabels=['one呵呵','two呵呵','three呵呵']
xticks(range(1,len(xlabels)+1),xlabels,rotation=45)
bar(a,b,color='k')
show()

可参考[3]

参考文献

[1] pyplot.show() fails to produce graph, causes IDLE to restart. https://stackoverflow.com/questions/5820102/pyplot-show-fails-to-produce-graph-causes-idle-to-restart?rq=1

[2] Using matplotlib in a python shell. https://matplotlib.org/1.5.3/users/shell.html

[3] Matplotlib输出中文显示问题. https://blog.csdn.net/u010758410/article/details/71743225

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值