科学计算与绘图:NumPy 和 Matplotlib 入门
1. 利用 NumPy 进行矩阵操作
在 Python 中,NumPy 是科学计算的核心包,许多其他专业包都基于它的功能构建。
1.1 安装 NumPy 和 SciPy
可以使用以下命令进行安装:
pip3 install numpy
pip3 install scipy
对于 32 位 Windows 或 Mac 系统,也可以下载最新版本并运行自动安装程序。64 位系统(包括 OS X 10.6 及更高版本)需要安装 64 位的 SciPy(包含 NumPy)。Debian/Ubuntu 用户可以通过以下命令安装 NumPy:
sudo apt-get install python-numpy
1.2 NumPy 数组与 Python 列表的对比
在 Python 中,我们通常用“列表的列表”来表示二维矩阵:
matrix = [[1,2,3], [4,5,6], [7,8,9]]
print(matrix)
输出结果为:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
若要访问矩阵中的元素,可以使用索引:
print(matrix[0][1])
输出结果为:
2
然而,如果要对矩阵中的每个元素进行操作,如将每个元素乘以 2,则需要嵌套循环。
使用 NumPy 可以更方便地处理矩阵:
from numpy import array
matrix = array([[1,2,3], [4,5,6], [7,8,9]])
print(matrix)
输出结果为:
[[1 2 3]
[4 5 6]
[7 8 9]]
同样可以使用索引访问元素:
print(matrix[0][1])
print(matrix[0,1])
输出结果均为:
2
NumPy 数组与 Python 列表的不同之处在于,数组只能包含相似类型的元素(如所有元素都是数字),而列表可以包含任意类型的对象。在 NumPy 中,数组的每个维度称为轴(axis),数组的总维度数或轴数称为矩阵的“秩”(rank)。
以下是创建三维数组的示例:
matrix = [
[ [1,2,3], [4,5,6] ],
[ [7,8,9], [10,11,12] ],
[ [13,14,15], [16,17,18] ]
]
print(matrix[0][1][2])
输出结果为:
6
1.3 NumPy 数组的操作
- 元素乘法 :
from numpy import array
matrix = array([[1,2,3], [4,5,6], [7,8,9]])
print(matrix*2)
输出结果为:
[[ 2 4 6]
[ 8 10 12]
[14 16 18]]
- 矩阵加减法 :
second_matrix = array([[5,4,3], [7,6,5], [9,8,7]])
print(second_matrix - matrix)
输出结果为:
[[ 4 2 0]
[ 3 1 -1]
[ 2 0 -2]]
- 矩阵对应元素乘法 :
print(second_matrix * matrix)
输出结果为:
[[ 5 8 9]
[28 30 30]
[63 64 63]]
- 矩阵点积 :
from numpy import dot
print(dot(second_matrix, matrix))
输出结果为:
[[ 42 54 66]
[ 66 84 102]
[ 90 114 138]]
- 矩阵堆叠 :
from numpy import vstack, hstack
print(vstack([matrix, second_matrix]))
print(hstack([matrix, second_matrix]))
输出结果分别为:
[[1 2 3]
[4 5 6]
[7 8 9]
[5 4 3]
[7 6 5]
[9 8 7]]
[[1 2 3 5 4 3]
[4 5 6 7 6 5]
[7 8 9 9 8 7]]
1.4 NumPy 数组的属性和函数
- 形状(shape) :
print(matrix.shape)
输出结果为:
(3, 3)
- 对角线元素(diagonal) :
print(matrix.diagonal())
输出结果为:
[1 5 9]
- 扁平化(flatten) :
print(matrix.flatten())
输出结果为:
[1 2 3 4 5 6 7 8 9]
- 转置(transpose) :
print(matrix.transpose())
输出结果为:
[[1 4 7]
[2 5 8]
[3 6 9]]
- 最小值(min) :
print(matrix.min())
输出结果为:
1
- 最大值(max) :
print(matrix.max())
输出结果为:
9
- 平均值(mean) :
print(matrix.mean())
输出结果为:
5.0
- 总和(sum) :
print(matrix.sum())
输出结果为:
45
- 重塑(reshape) :
print(matrix.reshape(9,1))
输出结果为:
[[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]]
1.5 创建多维数组
可以使用
arange()
和
reshape()
函数更方便地创建多维数组:
from numpy import arange
matrix = arange(1,10)
matrix = matrix.reshape(3,3)
print(matrix)
输出结果为:
[[1 2 3]
[4 5 6]
[7 8 9]]
1.6 随机数组
NumPy 还提供了随机数生成功能:
from numpy import random
print(random.random([3,3]))
以下是 NumPy 操作的流程图:
graph TD;
A[安装 NumPy 和 SciPy] --> B[创建数组];
B --> C[数组操作];
C --> D[元素乘法];
C --> E[矩阵加减法];
C --> F[矩阵对应元素乘法];
C --> G[矩阵点积];
C --> H[矩阵堆叠];
B --> I[数组属性和函数];
I --> J[形状];
I --> K[对角线元素];
I --> L[扁平化];
I --> M[转置];
I --> N[最小值];
I --> O[最大值];
I --> P[平均值];
I --> Q[总和];
I --> R[重塑];
B --> S[创建多维数组];
B --> T[随机数组];
2. 使用 Matplotlib 绘图
Matplotlib 库与 NumPy 结合使用,可用于创建各种二维图形,以可视化数据。
2.1 安装 Matplotlib
可以使用以下命令进行安装:
pip3 install numpy
pip3 install matplotlib
Windows 和 OS X 用户也可以下载自动安装程序。Debian/Linux 用户可以通过以下命令安装:
sudo apt-get install python-matplotlib
2.2 绘制简单图形
from matplotlib import pyplot as plt
plt.plot([1,2,3,4,5], [2,4,6,8,10])
plt.show()
当调用
plt.show()
时,会弹出一个新窗口,显示由五个 (x, y) 点组成的图形。
如果不指定 x 轴坐标,Matplotlib 会默认使用从 0 开始的顺序整数作为 x 轴坐标:
from matplotlib import pyplot as plt
plt.plot([2,4,6,8,10])
plt.show()
2.3 绘图格式
可以在
plot()
函数中使用可选的“格式”参数来指定线条或点的颜色和样式。默认值为“实心蓝色线”,用格式字符串
b-
表示。例如,要绘制由实心线连接的绿色圆点,可以使用格式字符串
g-o
:
from matplotlib import pyplot as plt
plt.plot([2,4,6,8,10], "g-o")
plt.show()
2.4 绘制多个数据集
from matplotlib import pyplot as plt
from numpy import arange
x_points = arange(1,21)
baseline = arange(0,20)
plt.plot(x_points, baseline**2, "g-o", x_points, baseline, "r-^")
plt.show()
2.5 改进图形布局和格式
- 设置坐标轴范围 :
from matplotlib import pyplot as plt
from numpy import arange
x_points = arange(1,21)
baseline = arange(0,20)
plt.plot(x_points, baseline**2, "g-o", x_points, baseline, "r-^")
plt.axis([0, 21, 0, 400])
plt.show()
- 添加标题、标签和图例 :
from matplotlib import pyplot as plt
from numpy import arange
x_points = arange(1,21)
baseline = arange(0,20)
plt.plot(x_points, baseline**2, "g-o", x_points, baseline, "r-^")
plt.axis([0, 21, 0, 400])
plt.title("Amount of Python learned over time")
plt.xlabel("Days")
plt.ylabel("Standardized knowledge index score")
plt.legend(("Real Python", "Other course"), loc=2)
plt.show()
2.6 绘制条形图
from matplotlib import pyplot as plt
from numpy import arange
plt.bar(arange(0,10), arange(1,21,2))
plt.show()
可以通过设置
width
参数来改变条形的宽度:
from matplotlib import pyplot as plt
from numpy import arange
plt.bar(arange(0,10), arange(1,21,2), width=.5)
plt.show()
若要在同一图中比较多组条形图,需要在 x 轴上进行间隔排列:
from matplotlib import pyplot as plt
from numpy import arange
plt.bar(arange(0,10)*2, arange(1,21,2))
plt.bar(arange(0,10)*2 + 1, arange(1,31,3), color="red")
plt.show()
可以使用
xticks()
函数设置 x 轴标签:
from matplotlib import pyplot as plt
from numpy import arange
plt.bar(arange(0,10)*3, arange(1,21,2))
plt.bar(arange(0,10)*3 + 1, arange(1,31,3), color="red")
plt.xticks(arange(0,10)*3 + 1, arange(1,11), fontsize=20)
plt.show()
2.7 绘制直方图
from matplotlib import pyplot as plt
from numpy import random
plt.hist(random.randn(10000), 20)
plt.show()
2.8 添加注释和数学表达式
可以使用
annotate()
函数在图形上添加注释:
from matplotlib import pyplot as plt
from numpy import random
plt.hist(random.randn(10000), 20)
plt.annotate("expected mean", xy=(0, 0), xytext=(0, 300), ha="center",
arrowprops=dict(facecolor='black'), fontsize=20)
plt.show()
可以使用 TeX 标记语言在注释中包含数学表达式:
from matplotlib import pyplot as plt
from numpy import random
plt.hist(random.randn(10000), 20)
plt.annotate(r"$\hat \mu = 0$", xy=(0, 0), xytext=(0, 300), ha="center",
arrowprops=dict(facecolor='black'), fontsize=20)
plt.show()
2.9 保存图形
可以使用
savefig()
函数将图形保存为 PNG、SVG、PDF 或 PostScript 文件:
from matplotlib import pyplot as plt
from numpy import random
plt.hist(random.randn(10000), 20)
path = "C:/book1-exercises/chp14"
plt.savefig(path + "histogram.png")
plt.savefig(path + "histogram.pdf")
2.10 交互式绘图
如果需要在不重新运行整个脚本的情况下修改图形,可以使用
ion()
函数开启 Matplotlib 的交互式模式:
from matplotlib import pyplot as plt
plt.ion()
以下是 Matplotlib 绘图的流程图:
graph TD;
A[安装 Matplotlib] --> B[导入 pyplot];
B --> C[绘制简单图形];
C --> D[指定 x 和 y 坐标];
C --> E[默认 x 坐标];
B --> F[绘图格式];
B --> G[绘制多个数据集];
B --> H[改进图形布局和格式];
H --> I[设置坐标轴范围];
H --> J[添加标题、标签和图例];
B --> K[绘制条形图];
K --> L[设置条形宽度];
K --> M[比较多组条形图];
K --> N[设置 x 轴标签];
B --> O[绘制直方图];
B --> P[添加注释和数学表达式];
B --> Q[保存图形];
B --> R[交互式绘图];
3. 复习练习
3.1 NumPy 练习
-
使用
arange()和reshape()创建一个 3x3 的 NumPy 数组first_matrix,包含数字 3 到 11。
from numpy import arange
first_matrix = arange(3, 12).reshape(3, 3)
print(first_matrix)
-
显示
first_matrix中所有元素的最小值、最大值和平均值。
print("最小值:", first_matrix.min())
print("最大值:", first_matrix.max())
print("平均值:", first_matrix.mean())
-
使用
**运算符将first_matrix中的每个元素平方,并将结果保存到数组second_matrix中。
second_matrix = first_matrix ** 2
print(second_matrix)
-
使用
vstack()将first_matrix堆叠在second_matrix上方,并将结果保存到数组third_matrix中。
from numpy import vstack
third_matrix = vstack([first_matrix, second_matrix])
print(third_matrix)
-
使用
dot()计算third_matrix与first_matrix的点积。
from numpy import dot
result = dot(third_matrix, first_matrix)
print(result)
-
将
third_matrix重塑为 3x3x2 的数组。
reshaped_matrix = third_matrix.reshape(3, 3, 2)
print(reshaped_matrix)
3.2 Matplotlib 练习
- 不参考提供的代码,编写自己的脚本重新创建本节中显示的所有图形。
-
编写一个脚本
pirates.py来直观地研究世界上海盗数量与全球气温上升之间的关系:
import csv
import matplotlib.pyplot as plt
# 读取数据
pirates = []
temperatures = []
years = []
with open('pirates.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # 跳过标题行
for row in reader:
pirates.append(int(row[0]))
temperatures.append(float(row[1]))
years.append(int(row[2]))
# 绘制折线图
plt.plot(pirates, temperatures)
# 添加标题和标签
plt.title('Relationship between Pirates and Global Temperature')
plt.xlabel('Number of Pirates')
plt.ylabel('Average World Temperature (°C)')
# 标注每个点的年份
for i in range(len(pirates)):
plt.annotate(str(years[i]), (pirates[i], temperatures[i]))
# 保存图形
plt.savefig('pirates_temperature.png')
# 显示图形
plt.show()
通过以上内容,我们学习了如何使用 NumPy 进行矩阵操作和使用 Matplotlib 进行数据可视化。这些工具在科学计算和数据分析中非常有用,可以帮助我们更高效地处理和展示数据。
科学计算与绘图:NumPy 和 Matplotlib 入门
4. 深入理解 NumPy 和 Matplotlib 的应用场景
4.1 NumPy 在不同领域的应用
- 游戏开发 :在游戏开发中,常常需要处理二维或多维的网格数据,例如地图、角色位置等。使用 NumPy 数组可以方便地存储和操作这些数据。比如,开发一个简单的棋盘游戏,棋盘可以用一个二维的 NumPy 数组来表示,每个元素代表棋盘上的一个格子状态。
from numpy import zeros
# 创建一个 8x8 的棋盘,初始状态都为 0
board = zeros((8, 8))
print(board)
- 图像处理 :图像可以看作是一个二维或三维的数组,其中二维数组表示灰度图像,三维数组表示彩色图像(通常是 RGB 三个通道)。NumPy 可以用于图像的基本处理,如调整亮度、对比度等。
from numpy import array
import cv2
# 读取图像
image = cv2.imread('example.jpg')
# 将图像转换为 NumPy 数组
image_array = array(image)
# 调整亮度,将每个像素值乘以 1.5
brightened_image = image_array * 1.5
# 确保像素值在 0 - 255 范围内
brightened_image = brightened_image.clip(0, 255).astype('uint8')
# 显示调整后的图像
cv2.imshow('Brightened Image', brightened_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
4.2 Matplotlib 在数据可视化中的优势
- 数据探索 :在进行数据分析时,首先需要对数据有一个直观的了解。Matplotlib 可以快速地绘制各种图形,帮助我们发现数据中的模式、趋势和异常值。例如,在分析销售数据时,可以绘制折线图来观察销售额随时间的变化趋势。
from matplotlib import pyplot as plt
import numpy as np
# 模拟销售数据
months = np.arange(1, 13)
sales = np.array([100, 120, 130, 150, 160, 180, 200, 220, 230, 250, 260, 280])
# 绘制折线图
plt.plot(months, sales)
plt.title('Monthly Sales Trend')
plt.xlabel('Month')
plt.ylabel('Sales Amount')
plt.show()
- 报告与展示 :在向他人展示数据分析结果时,清晰、美观的可视化图形可以更有效地传达信息。Matplotlib 提供了丰富的定制选项,可以创建高质量的图形,满足不同的展示需求。例如,在制作商业报告时,可以绘制柱状图来比较不同产品的销售额。
from matplotlib import pyplot as plt
import numpy as np
# 模拟不同产品的销售额
products = ['Product A', 'Product B', 'Product C', 'Product D']
sales = np.array([200, 300, 150, 250])
# 绘制柱状图
plt.bar(products, sales)
plt.title('Sales Comparison of Different Products')
plt.xlabel('Product')
plt.ylabel('Sales Amount')
plt.show()
5. 高级 NumPy 和 Matplotlib 技巧
5.1 NumPy 的高级数组操作
- 布尔索引 :布尔索引允许我们根据条件筛选数组中的元素。例如,筛选出数组中大于 5 的元素。
from numpy import array
arr = array([1, 6, 3, 8, 4, 9])
# 筛选出大于 5 的元素
filtered_arr = arr[arr > 5]
print(filtered_arr)
- 广播机制 :广播机制是 NumPy 中一个强大的特性,它允许不同形状的数组进行算术运算。例如,将一个一维数组加到一个二维数组的每一行。
from numpy import array
matrix = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
vector = array([1, 1, 1])
# 广播操作,将向量加到矩阵的每一行
result = matrix + vector
print(result)
5.2 Matplotlib 的高级绘图技巧
- 子图绘制 :在一个图形窗口中绘制多个子图可以同时展示不同的数据或不同的分析结果。例如,在一个窗口中同时绘制折线图和柱状图。
from matplotlib import pyplot as plt
import numpy as np
# 生成数据
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
# 创建一个 1 行 2 列的子图布局
fig, axes = plt.subplots(1, 2)
# 在第一个子图中绘制正弦曲线
axes[0].plot(x, y1)
axes[0].set_title('Sine Curve')
# 在第二个子图中绘制余弦曲线
axes[1].plot(x, y2)
axes[1].set_title('Cosine Curve')
plt.show()
- 颜色映射 :颜色映射可以为图形中的数据点或区域赋予不同的颜色,以表示数据的大小或其他属性。例如,在绘制热力图时,可以使用颜色映射来表示不同区域的数据值。
from matplotlib import pyplot as plt
import numpy as np
# 生成一个 10x10 的随机矩阵
data = np.random.rand(10, 10)
# 绘制热力图
plt.imshow(data, cmap='hot')
plt.colorbar()
plt.show()
6. 总结与展望
6.1 总结
通过本文的学习,我们全面了解了 NumPy 和 Matplotlib 的基本功能和使用方法。NumPy 提供了强大的数组操作能力,使得矩阵运算变得简单高效;Matplotlib 则为数据可视化提供了丰富的工具,可以创建各种类型的图形。在实际应用中,NumPy 和 Matplotlib 常常结合使用,帮助我们更好地处理和展示数据。
| 工具 | 主要功能 | 应用场景 |
|---|---|---|
| NumPy | 矩阵操作、数组存储和处理 | 科学计算、游戏开发、图像处理等 |
| Matplotlib | 数据可视化,创建各种图形 | 数据分析、报告展示、数据探索等 |
6.2 展望
NumPy 和 Matplotlib 作为 Python 中科学计算和数据可视化的重要工具,未来还将不断发展和完善。随着人工智能和机器学习的快速发展,对大规模数据处理和可视化的需求也越来越高。NumPy 可能会进一步优化性能,支持更高效的并行计算;Matplotlib 可能会提供更多的交互功能和更美观的图形样式。同时,与其他数据分析和机器学习库的集成也将更加紧密,为用户提供更便捷的一站式解决方案。
总之,掌握 NumPy 和 Matplotlib 是进行科学计算和数据分析的基础,希望本文能够帮助读者更好地使用这两个工具,在实际工作中发挥更大的作用。
超级会员免费看

被折叠的 条评论
为什么被折叠?



