文章目录

  • 前言
  • 问题描述
  • 原因分析
  • 1)失败尝试
  • 2)正确尝试
  • 3)解决方案
  • 4)补充知识
  • 补充问题:如何在matplotlib作图中显示中文
  • 1)问题描述
  • 2)解决方案
  • 参考文献


前言

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

问题描述

python画图没显示 python画图运行不了_显示中文

即:我在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中运行同样的代码,结果如下:

python画图没显示 python画图运行不了_python_02

原因分析

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)补充知识

给出了很多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()

结果是:

python画图没显示 python画图运行不了_python_03

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

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] Matplotlib输出中文显示问题.