📜  Python| Matplotlib 简介(1)

📅  最后修改于: 2023-12-03 14:46:20.922000             🧑  作者: Mango

Python | Matplotlib 简介

Matplotlib 是 python 中一个用于绘制图形的库,它可以做非常多的事情,包括绘制线形图、散点图、等高线图、条形图、误差条形图、直方图、极坐标图、子图和多个图表。Matplotlib 也支持将图片嵌入到 GUI 应用程序中。

安装

Matplotlib 可以通过 pip 命令进行安装:

pip install matplotlib
绘制简单折线图

使用 Matplotlib 绘制简单折线图的步骤如下:

  1. 导入 Matplotlib 模块:使用 import 语句导入 Matplotlib 模块;
  2. 创建画布和子图:使用 subplots 函数创建画布和子图对象;
  3. 绘制数据:使用 plot 函数绘制数据;
  4. 添加标题和标签:使用 titlexlabelylabel 函数添加标题和标签;
  5. 显示图像:使用 show 函数显示图像。

下面是一个简单折线图的代码示例:

import matplotlib.pyplot as plt

# 创建画布和子图
fig, ax = plt.subplots()

# 绘制数据
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])

# 添加标题和标签
ax.set_title('Simple Line Plot')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')

# 显示图像
plt.show()

运行上面的代码可以得到一个简单的折线图,如下图所示:

Simple Line Plot

绘制散点图

使用 Matplotlib 绘制散点图的步骤与绘制简单折线图类似,不同的是需要使用 scatter 函数绘制数据,下面是一个简单散点图的代码示例:

import matplotlib.pyplot as plt

# 创建画布和子图
fig, ax = plt.subplots()

# 绘制数据
ax.scatter([1, 2, 3, 4], [1, 4, 2, 3])

# 添加标题和标签
ax.set_title('Simple Scatter Plot')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')

# 显示图像
plt.show()

运行上面的代码可以得到一个简单的散点图,如下图所示:

Simple Scatter Plot

绘制直方图

使用 Matplotlib 绘制直方图的步骤与绘制简单折线图类似,不同的是需要使用 hist 函数绘制数据,下面是一个简单直方图的代码示例:

import matplotlib.pyplot as plt
import numpy as np

# 创建画布和子图
fig, ax = plt.subplots()

# 随机生成 1000 个数据
np.random.seed(0)
x = np.random.randn(1000)

# 绘制数据
ax.hist(x, bins=50)

# 添加标题和标签
ax.set_title('Simple Histogram Plot')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')

# 显示图像
plt.show()

运行上面的代码可以得到一个简单的直方图,如下图所示:

Simple Histogram Plot

总结

Matplotlib 是一个非常强大的图形库,可以用于绘制各种类型的图形。本文介绍了如何使用 Matplotlib 绘制简单折线图、散点图和直方图,读者可以根据自己的需求通过学习 Matplotlib 来使用更多的功能。