create account

每天进步一点点:解决Matplotlib绘图中的几个问题 by oflyhigh

View this thread on: hive.blogpeakd.comecency.com
· @oflyhigh ·
$79.07
每天进步一点点:解决Matplotlib绘图中的几个问题
好多天前,分享了一下在电脑上运行自己十多年前写的代码,其核心就是使用Python+matplotlib绘图。matplotlib是一个非常强大的综合库,用于在 Python 中创建静态、动画和交互式可视化程序。

![image.png](https://images.hive.blog/DQmPQVkwTyjuqZgb9w6QZ7MiGRFwLS73NiNcZZiujsfsSDj/image.png)
(图源 :[pixabay](https://pixabay.com/photos/lightbulb-idea-creativity-base-3104355/))

最近又把matplotlib找出来使用,不曾想却遇到几个问题(忘记N年前是如何解决的啦),经过一番学习和探索,总算把这几个拦路虎摆平啦,记录下来以免遗忘,也希望能帮到后来者。

# 安装

使用之前,我们首先需要在Python虚拟运行环境中安装Matplotlib,指令如下:
>`pip install matplotlib`

# 解决`plt.show()`失败问题

安装成功后,如果我们直接去尝试官网中的例子,代码如下:
```
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 200)
y = np.sin(x)

fig, ax = plt.subplots()
ax.plot(x, y)
plt.show() 
```

那么接下来我们可能会受到一些打击。

比如说,我就遇到了如下错误:
>UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown plt.show()

这个问题简单来讲就是需要安装GUI支持,以便Matplotlib能够显示图像,具体内容请参考[文末链接](https://stackoverflow.com/questions/56656777/userwarning-matplotlib-is-currently-using-agg-which-is-a-non-gui-backend-so)。

我这使用如下方案可以完美解决:
>`pip install pyqt5`


接下来我们再次用官网示例中的例子测试一下我们的安装是否有问题。

运行示例,我们将会得到如下图形:
![image.png](https://images.hive.blog/DQmedj8PFGX8UfnDMn5QVYAW3qfXCnVrwdEVvRZzM6DTJSA/image.png)

是不是很神奇呀?

# 解决中文显示的问题(临时方案)

下面我们来运行如下代码:
```
import matplotlib.pyplot as plt
x = [1,2,3] 
y = [5,-7,8] 
plt.plot(x, y) 
plt.xlabel('x - 轴') 
plt.ylabel('y - 轴') 
plt.title('简单图形') 
plt.show() 
```

代码很简单,不做过多解释了。

但是运行代码我们得到的图形却是这个样子的:
![image.png](https://images.hive.blog/DQmXFfiYRjrEYD1vTKFqhykVUacyWLHkYVVyoKzVfNLt1u7/image.png)

有没有觉得哪里不正常?没错,我们添加的中文信息,都显示成乱码啦!并且命令行中也会出现类似如下的错误提示:
>UserWarning: Glyph 21333 (\N{CJK UNIFIED IDEOGRAPH-5355}) missing from current font.
  plt.show()

临时解决方法:
>`plt.rcParams['font.sans-serif']=['Microsoft YaHei']`

其中'Microsoft YaHei'是我系统中的中文字体之一。
(可以在C:\Users\xxxx\.matplotlib\fontlist-v330.json中查看名称和定位等)

我们还可以添加这句代码来显示正常的负号:
>`plt.rcParams['axes.unicode_minus'] = False `

添加了如上两行代码后重新运行示例:
![image.png](https://images.hive.blog/DQmQohqqwJVC2G6gDSywZoGWtX5x7JAzyBBGSSqmCsGn2W7/image.png)

对比之前的图形,我们会发现:中文字符显示正确了,负号也变得更好看了,成功!

# 解决中文显示的问题(永久方案)

通过增加如下两行代码的方式,我们成功地解决了中文字符以及负号(`-`)的正确显示问题:
>`plt.rcParams['font.sans-serif']=['Microsoft YaHei']`
>`plt.rcParams['axes.unicode_minus'] = False`

但是这个方案有个缺点,我们每写一段新代码,都不得不在代码中加入上述语句,否则中文字符就会再次以乱码形式出现,负号也变成了难看的样子。

那么有没有什么一劳永逸的方法呢?答案是有的,那就是修改matplotlib的配置文件,以我的电脑为例,路径如下:
>`E:\Study\.venv\Lib\site-packages\matplotlib\mpl-data`

#### 中文字符
打开其中的`matplotlibrc`文件,找到这行:
`#font.sans-serif:  DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif`

去掉前边的`#`,并在其中加入`Microsoft YaHei,` 修改完成后是这个样子:
>`font.sans-serif:  Microsoft YaHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif`

#### 负号问题

找到以下这行:
>`#axes.unicode_minus: True  # use Unicode for the minus symbol rather than hyphen.  See`

去掉`#`并把值从True改为False,修改完成后是这个样子:
>`axes.unicode_minus: False  # use Unicode for the minus symbol rather than hyphen.  See`

再来测试如下代码(没额外增加设置语句):
```
import matplotlib.pyplot as plt
x = [1,2,3] 
y = [5,-7,8] 
plt.plot(x, y) 
plt.xlabel('x - 轴') 
plt.ylabel('y - 轴') 
plt.title('简单图形') 
plt.show() 
```

输出图形如下:
![Figure_1.png](https://images.hive.blog/DQmbDziBzXbUjmDTzBuLiC74eHfwCm8T7pXCJi8NNmFVYG9/Figure_1.png)

总算解决Matplotlib绘图中遇到的问题啦,以后可以愉快地玩耍啦。



# 相关链接
* https://matplotlib.org/stable/users/getting_started/
* ["UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm](https://stackoverflow.com/questions/56656777/userwarning-matplotlib-is-currently-using-agg-which-is-a-non-gui-backend-so)
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 192 others
properties (23)
authoroflyhigh
permlinkmatplotlib
categoryhive-105017
json_metadata{"tags":["cn","life","blog","python","matplotlib","study","cn-progamming"],"image":["https://images.hive.blog/DQmPQVkwTyjuqZgb9w6QZ7MiGRFwLS73NiNcZZiujsfsSDj/image.png","https://images.hive.blog/DQmedj8PFGX8UfnDMn5QVYAW3qfXCnVrwdEVvRZzM6DTJSA/image.png","https://images.hive.blog/DQmXFfiYRjrEYD1vTKFqhykVUacyWLHkYVVyoKzVfNLt1u7/image.png","https://images.hive.blog/DQmQohqqwJVC2G6gDSywZoGWtX5x7JAzyBBGSSqmCsGn2W7/image.png","https://images.hive.blog/DQmbDziBzXbUjmDTzBuLiC74eHfwCm8T7pXCJi8NNmFVYG9/Figure_1.png"],"links":["https://pixabay.com/photos/lightbulb-idea-creativity-base-3104355/"],"app":"hiveblog/0.1","format":"markdown"}
created2023-11-04 09:54:51
last_update2023-11-04 09:54:51
depth0
children5
last_payout2023-11-11 09:54:51
cashout_time1969-12-31 23:59:59
total_payout_value39.556 HBD
curator_payout_value39.509 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length3,698
author_reputation6,267,635,002,292,573
root_title每天进步一点点:解决Matplotlib绘图中的几个问题
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id128,568,613
net_rshares160,112,233,014,217
author_curate_reward""
vote details (256)
@annepink ·
每天进步!O哥进步小能手!只能仰望O神啊!
@tipu curate
properties (22)
authorannepink
permlinkparama-1699103837725
categoryhive-105017
json_metadata""
created2023-11-04 13:17:21
last_update2023-11-04 13:17:21
depth1
children1
last_payout2023-11-11 13:17:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length34
author_reputation1,027,406,686,392,248
root_title每天进步一点点:解决Matplotlib绘图中的几个问题
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id128,571,936
net_rshares0
@tipu ·
<a href="https://tipu.online/hive_curator?annepink" target="_blank">Upvoted  &#128076;</a> (Mana: 8/48) <a href="https://peakd.com/hive/@reward.app/reward-app-quick-guide-updated" target="_blank">Liquid rewards</a>.
properties (22)
authortipu
permlinkre-parama-1699103837725-20231104t131726z
categoryhive-105017
json_metadata"{"app": "beem/0.24.26"}"
created2023-11-04 13:17:27
last_update2023-11-04 13:17:27
depth2
children0
last_payout2023-11-11 13:17:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length215
author_reputation55,905,961,568,182
root_title每天进步一点点:解决Matplotlib绘图中的几个问题
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id128,571,938
net_rshares0
@love5200 ·
我要能有O哥一半的学习态度,早就上清北了。。。😂佩服佩服。
properties (22)
authorlove5200
permlinkre-oflyhigh-2023114t214010651z
categoryhive-105017
json_metadata{"tags":["cn","life","blog","python","matplotlib","study","cn-progamming"],"app":"ecency/3.0.36-vision","format":"markdown+html"}
created2023-11-04 13:40:18
last_update2023-11-04 13:40:18
depth1
children0
last_payout2023-11-11 13:40:18
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length29
author_reputation536,562,363,254,952
root_title每天进步一点点:解决Matplotlib绘图中的几个问题
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id128,572,279
net_rshares0
@lovelingling ·
解决问题就像做一道数学题一样,其中的喜悦也只有当事人才能感受到。待在舒适区久了,很长时间没这感觉了。😂
properties (22)
authorlovelingling
permlinkparama-1699094653227
categoryhive-105017
json_metadata""
created2023-11-04 10:44:15
last_update2023-11-04 10:44:15
depth1
children0
last_payout2023-11-11 10:44:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length51
author_reputation716,623,616,587,841
root_title每天进步一点点:解决Matplotlib绘图中的几个问题
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id128,569,313
net_rshares0
@xiaoyaodidi ·
看O哥的代码贴 就是我的精神食粮 边吃饭边看 不亦乐乎😄
properties (22)
authorxiaoyaodidi
permlinkre-oflyhigh-2023114t12342043z
categoryhive-105017
json_metadata{"type":"comment","tags":["hive-105017","cn","life","blog","python","matplotlib","study","cn-progamming"],"app":"ecency/3.0.44-mobile","format":"markdown+html"}
created2023-11-04 11:34:21
last_update2023-11-04 11:34:21
depth1
children0
last_payout2023-11-11 11:34:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length28
author_reputation420,068,217,197,428
root_title每天进步一点点:解决Matplotlib绘图中的几个问题
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id128,569,951
net_rshares0