简介
matplotlib 是一个数学绘图库, 可用来制作简单的图表, 如折线图和散点图等等.
安装matplotlib
mac
# -i https://pypi.mirrors.ustc.edu.cn/simple/ 临时访问国内镜像
pip3 install --user matplotlib -i https://pypi.mirrors.ustc.edu.cn/simple/
测试 matplotlib
wushanghuideMacBook-Pro:~ wushanghui$ python3
Python 3.8.5 (default, Jul 21 2020, 10:48:26)
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>>
matplotlib 画廊
查看使用matplotlib制作各种图表, 访问https://matplotlib.org/ 的示例画廊.
绘制折线图
mpl_squares.py
import matplotlib.pyplot as plt
input_value = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
# 绘制图形,linewidth是线条粗细
plt.plot(input_value, squares, linewidth=5)
# 设置图标标题,并给坐标轴加上标签 标题有中文报错
plt.title("Square Numbers", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
# 设置刻度标记的大小(就是样式)
plt.tick_params(axis='both', labelsize=14)
# 打开matplotlib查看器
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TWVvhQaQ-1637590467400)(/upload/2020/11/image-0d9f61e69b7443bfafb181baaa799180.png)][外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9joy3Zv4-1637590467401)(/Users/wushanghui/Library/Application Support/typora-user-images/image-20201113215700983.png)]
使用scatter()绘制散点图
scatter_squares.py
import matplotlib.pyplot as plt
# 使用scatter()绘制散点图并设置其样式
x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]
plt.scatter(x_values, y_values, s=100)
# 设置图标标题,并给坐标轴加上标签 这个标题给中文报错了,暂时不明白
plt.title("Square Numbers", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
# 设置刻度标记的大小(就是样式)
plt.tick_params(axis='both', which='major', labelsize=14)
# 打开matplotlib查看器
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7ab1bFg0-1637590467402)(/upload/2020/11/image-1949d34a254f4ede9ead0b029ee2dc7a.png)]
自动计算数据
scatter_squares2.py
import matplotlib.pyplot as plt
# 自动计算数据
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
# matplotlib 在2.0.0版本中, edgecolor这个实参默认就为none
# 线条颜色可以 c='red' 这样指定,也可以自定义c=(0, 0, 0.8)
# c=y_values, cmap=plt.cm.Blues 这是使用了颜色映射
# y值较小的点显示为浅蓝色,较大的显示为深蓝色
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolor='none', s=40)
# 设置图标标题,并给坐标轴加上标签 这个标题给中文报错了,暂时不明白
plt.title("Square Numbers", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Square of Value', fontsize=14)
# 设置刻度标记的大小(就是样式)
plt.tick_params(axis='both', which='major', labelsize=14)
# 设置每个坐标轴的取值范围
plt.axis([0, 1100, 0, 1100000])
# 打开matplotlib查看器
# plt.show()
# 自动保存图标
# 'squares_plot.png' 当前脚本的所在目录保存 squares_plot.png 文件
# bbox_inches='tight' 表示将空白的区域裁剪掉
plt.savefig('squares_plot.png', bbox_inches='tight')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7TC7NfMt-1637590467403)(/upload/2020/11/image-f0903e4c4cb2422bbfea53c55fd7a512.png)]
随机漫步
random_walk.py
from random import choice
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
self.num_points = num_points
# 所有随机漫步都始于(0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""计算随机漫步包含的所有点"""
# 不断漫步,知道列表达到指定的长度
while len(self.x_values) < self.num_points:
# choice() 随机选择列表中的一个数
# 决定前进方向以及沿这个方向前进的距离
# x 的方向
x_direction = choice([1, -1])
# x 的距离
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
# 拒绝原地踏步
if x_step == 0 and y_step == 0:
continue
# 计算下一个点的x和y值
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
rw_visual.py
import matplotlib.pyplot as plt
from random_walk import RandomWalk
# 只要程序处于活动状态,就不断地模拟随机漫步
while True:
# 创建一个RandomWalk实例,并将其包含的点都绘制出来
rw = RandomWalk(50000)
rw.fill_walk()
# 设置绘图窗口的尺寸
plt.figure(dpi=256, figsize=(10, 6))
point_numbers = list(range(rw.num_points))
# 给点着色看出漫步的轨迹
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=1)
# 突出起点和终点
plt.scatter(0, 0, c='green', edgecolor='none', s=100)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolor='none', s=100)
# 隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
keep_running = input("是否再模拟一次随机漫步?(y/n):")
if keep_running == 'n':
break
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-K1oqvXYz-1637590467404)(/upload/2020/11/image-bb7714a2ad8547f8b59610b97231d356.png)]
Python3 目录