matplotlib使用笔记

Matplotlib 是 Python 的一个绘图库。它包含了大量的工具,你可以使用这些工具创建各种图形,包括简单的散点图,正弦曲线,甚至是三维图形。Python 科学计算社区经常使用它完成数据可视化的工作。

线性图

最简单的线形图

首先导入相关的模块

import matplotlib.pyplot as plt
import numpy as np

绘制最简单的线性图

# 简单的绘图
x = np.linspace(0, 2 * np.pi, 50) #产生50个从小到大在区间[0,2PI]之间的数
plt.plot(x, np.sin(x)) # 如果没有第一个参数 x,图形的 x 坐标默认为数组的索引
plt.show() # 显示图形

运行后的图像如下所示:
matplotlib使用笔记

自定义图标外观

指定线条的外观

x = np.linspace(0, 2 * np.pi, 50)
plt.plot(x, np.sin(x), "r--") #红色线条,--线
plt.show() 

运行后的图像如下所示:
matplotlib使用笔记
颜色: 蓝色 - ‘b’ 绿色 - ‘g’ 红色 - ‘r’ 青色 - ‘c’ 品红 - ‘m’ 黄色 - ‘y’ 黑色 - ‘k’('b’代表蓝色,所以这里用黑色的最后一个字母) 白色 - ‘w’
线: 直线 - ‘-’ 虚线 - ‘–’ 点线 - ‘:’ 点划线 - ‘-.’ 常用点标记 点 - ‘.’ 像素 - ‘,’ 圆 - ‘o’ 方形 - ‘s’ 三角形 - ‘^’ 。更过线条标志请点击

指定轴的名称

x = np.linspace(0, 2 * np.pi, 50)
plt.plot(x, np.sin(x), 'r')
plt.xlabel("X label")
plt.ylabel("Y label")
plt.show()

运行后的图像如下所示:
matplotlib使用笔记

指定图的Legend

x = np.linspace(0, 2 * np.pi, 50)
plt.plot(x, np.sin(x), 'r')
plt.plot(x, np.cos(x), "y")
plt.xlabel("X label")
plt.ylabel("Y label")
# 使用legend绘制多条曲线
plt.legend(labels=['sin', 'cos'], loc='upper right')
plt.show()

运行后的图像如下所示:
matplotlib使用笔记

绘制子图

可以在一个视图内绘制多个图标

# 使用子图
x = np.linspace(0, 2 * np.pi, 50)
plt.subplot(2, 2, 1) # (行,列,活跃区)
plt.plot(x, np.sin(x), 'r')
plt.subplot(2, 2, 2)
plt.plot(x, np.cos(x), 'g')
plt.subplot(2, 2, 3)
plt.plot(x, np.tan(x), 'b')
plt.subplot(2, 2, 4)
plt.plot(x, np.tanh(x), "y")
plt.show()

运行后的图像如下所示:
matplotlib使用笔记

直方图

# 直方图
x = np.random.randn(100)
plt.hist(x, 10)
plt.show()

运行后的图像如下所示:

matplotlib使用笔记

显示图片

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('./test.png') #读取图片
plt.imshow(img)
plt.show()

运行后的图像如下所示:
matplotlib使用笔记

相关文章:

  • 2022-01-06
  • 2021-12-27
  • 2021-06-27
  • 2022-01-04
  • 2021-07-10
  • 2021-12-12
猜你喜欢
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-06
相关资源
相似解决方案