人工智能—Matplotlib学习
Matplotlib 是一个 Python 的2D绘图库,其中的pyplot需要经常用到,仅需要几行代码,便可以生成绘图,直方图,条形图,散点图,饼状图等。配合使用的库有numPy,pandas等。
安装
pip install matplotlib
导入
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
一、 函数用法
# 基础函数
plt.figure() 打开输出窗口
show()/imshow() 显示图像. 两者的区别在于 imshow 不仅可以显示图像,还可以显示其格式;show() 则仅会显示图像。
plot() 用来在 2D 平面上绘制点和线,并控制输出时的样式。
imread() 图像的读取
savefig() 保存图像
# 其他函数
subplot()/subplots() 一次在一个图像窗口中显示多张图片
plt.xlim()/plt.ylim() 对坐标轴的刻度范围进行限制
plt.xticks()/plt.yticks()
ax.set_xticks()/ax.set_yticks() 来对坐标轴上的刻度进行编辑
ax.set_xticklabels()
ax.set_yticklabels() 设置每个刻度对应的标签
ax.set_xlabel()
ax.set_ylabel()
plt.xlabel
plt.ylabel() 坐标轴标签和标题
ax.set_title()
plt.title() 来设置标题
ax.legend()
plt.legend() 添加图例
# 图的分类
plt.pie() 饼状图
plt.hist() 直方图
plt.bar() 柱状图,堆叠柱状图也是通过 plt.bar() 进行绘制,不同的是我们可以通过 bottom 参数指定某一个类别的柱的基底,从而实现柱的堆叠
plt.barh() 水平柱状图
plt.scatter() 散点图
二、代码示例
import matplotlib.pyplot as plt
import numpy as np
from numpy import ndarray
num_1 = [20, 30, 15, 35]
x_1 = [1.0, 2.0, 3.0, 4.0]
num_2 = [15, 30, 40, 20]
x_2 = [1.4, 2.4, 3.4, 4.4]
def bar_plot(x_1: ndarray, num_1: ndarray, x_2: ndarray, num_2: ndarray):
plt.bar(x_1,height=num_1,width=0.4,color='red',label='height')
plt.bar(x_2,height=num_2,width=0.4,color='blue',label='height')
plt.legend()
plt.show()
bar_plot(x_1, num_1, x_2, num_2)
运行结果
