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

二、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是界限

扫描二维码关注公众号,回复: 12624889 查看本文章
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()

猜你喜欢

转载自blog.csdn.net/joey_ro/article/details/109102230