python Matplotlib 系列教程—— 图例,标题和标签的使用

在上次一个简单的例子后,我们介绍一下如何使用图例,标题和标签。

数据是一个图表所要展示的东西,而图例,标题和标签则更加的帮助我们理解这个图表所包含的意义,是想要传递给我们什么信息。

import matplotlib.pyplot as plt

x1 = [1, 2, 3]
y1 = [1, 4, 9]

x2 = [1, 2, 3]
y2 = [5, 6, 7]

plt.plot(x1, y1, label=‘y=x*x’)
plt.plot(x2, y2, label=‘y=x+4’)

plt.xlabel(‘input number’)
plt.ylabel(‘ouput number’)

plt.title(‘测试某些函数’)

plt.legend()

plt.show()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

这段代码的执行结果如下:

这里写图片描述

有个很明显的问题,图表的title显示乱码,查看matplotlib文档发现,python中的matplotlib仅支持Unicode编码,默认是不显示中文的。

现提供一种解决方案,也是推荐解决方案:

1.首先要再python脚本中的开头加上后面的内容:#-- coding: utf-8 --,即用utf8编码。
2. 然后在代码中动态设置字体,
【注:低版本中x.label(u’x轴’);中文前需要加u;请注意】

#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)  

x1 = [1, 2, 3]
y1 = [1, 4, 9]

x2 = [1, 2, 3]
y2 = [5, 6, 7]

#绘制图形并设置要显示的图例文本

plt.plot(x1, y1, label=‘y=x*x’)
plt.plot(x2, y2, label=‘y=x+4’)

#绘制图形的x轴和y轴的轴名称
plt.xlabel(‘input number’)
plt.ylabel(‘ouput number’)

#绘制图形的标题
plt.title(u’测试某些函数’, fontproperties=font)

#显示图形的图例
plt.legend()

#显示图形
plt.show()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

这里写图片描述

现在我们就可以正常的显示中文啦。

                                </div><div data-report-view="{&quot;mod&quot;:&quot;1585297308_001&quot;,&quot;dest&quot;:&quot;https://blog.csdn.net/xjl271314/article/details/80291284&quot;,&quot;extend1&quot;:&quot;pc&quot;,&quot;ab&quot;:&quot;new&quot;}"><div></div></div>
            <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-60ecaf1f42.css" rel="stylesheet">
                            </div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值