机器学习——python基础二、Matplotlib 教程

本文介绍了如何在Python中使用Matplotlib进行2D绘图,包括基本的pylab接口介绍、安装与配置、关键函数如subplot、条形图和频率分布图示例。通过实例演示了如何设置中文字体和创建不同类型的图表。
摘要由CSDN通过智能技术生成

二、Matplotlib 教程

1.简介

Matplotlib 可能是 Python 2D-绘图领域使用最广泛的套件。它能让使用者很轻松地将数据图形化,并且提供多样化的输出格式。这里将会探索 matplotlib 的常见用法。

pylab 是 matplotlib 面向对象绘图库的一个接口。它的语法和 Matlab 十分相近。也就是说,它主要的绘图命令和 Matlab 对应的命令有相似的参数。

2.在python中使用
mac osX系统必须添加第二行否则会报错!
RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
必须将python的版本设为3.0

https://blog.csdn.net/joey_ro/article/details/109101392

必须引入中文字体要不然会报错

Matplotlib 默认情况不支持中文,我们可以使用以下简单的方法来解决。

这里我们使用思源黑体,思源黑体是 Adobe 与 Google 推出的一款开源字体。

官网:https://source.typekit.com/source-han-serif/cn/

GitHub 地址:https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese

你也可以在网盘下载: https://pan.baidu.com/s/14cRhgYvvYotVIFkRVd71fQ 提取码: e15r

可以下载个 OTF 字体,比如 SourceHanSansSC-Bold.otf,将该文件文件放在当前执行的代码文件中:

SourceHanSansSC-Bold.otf 文件放在当前执行的代码文件中:

# fname 为 你下载的字体库路径,注意 SourceHanSansSC-Bold.otf 字体的路径
zhfont1 = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")

3.一些重要函数

1)subplot在一张图上显示多个函数
# 计算正弦和余弦曲线上的点的 x 和 y 坐标
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
# 建立 subplot 网格,高为 2,宽为 1
# 激活第一个 subplot
plt.subplot(2, 1, 1)
# 绘制第一个图像
plt.plot(x, y_sin)
plt.title('正弦函数', fontproperties=zhfont1)
# 将第二个 subplot 激活,并绘制第二个图像
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('余弦函数', fontproperties=zhfont1)
# 展示图像
plt.show()

2)条形图
# bar函数生成条形图
x = [5, 8, 10]
y = [12, 16, 6]
x2 = [6, 9, 11]
y2 = [6, 15, 7]
plt.bar(x, y, align='center')
plt.bar(x2, y2, color='g', align='center')
plt.title('Bar graph')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
3)频率分布图

bin是界限

data = np.array(
    [1, 233, 45, 545, 543, 5, 34534, 5, 345, 34, 5, 34, 53, 45, 34, 5, 34, 5, 345, 3, 45, 34, 5, 34, 534, 5, 34])
plt.hist(data, bins=[0, 20, 40, 100])
plt.show()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值