matplotlib库的使用
1.pyplot
1)plot()函数的使用:生成一条简单折线
import matplotlib.pyplot as plt
input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.plot(input_values, squares, linewidth=4) # 根据输入输出生成简单折线 折线粗细设置
plt.title("Squares Number", fontsize=24) # 标题 字体大小设置
plt.xlabel("Value", fontsize=14) # 轴设置 字体大小设置
plt.ylabel("Square of Value", fontsize=14)
# 刻度的设置
plt.tick_params(axis='both', labelsize=14)
plt.show() # 显示所生成的图片
生成的图片如下:
2)scatter() 函数的使用 : 生成一个点或者一系列点
import matplotlib.pyplot as plt
"""from 1 to 1000"""
x_values = list(range(1, 101))
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolors='none', s=20)
# 此处的参数C 可为 ‘颜色’ or RGB 颜色模式(25,36,74) or 某个列表
# 颜色映射 参数cmap 告诉 pyplot 使用哪个颜色映射
# edgecolor 制定各个点的颜色,默认 蓝色点 黑色轮廓 none 则删除颜色点的轮廓
# s设置点的大小
plt.title("Square Number", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
# 参数axis的值为’x’、’y’、’both’,
# 分别代表设置X轴、Y轴以及同时设置,默认值为’both’。
# 参数which的值为 ‘major’、’minor’、’both’,
# 分别代表设置主刻度线、副刻度线以及同时设置,默认值为’major’
plt.axis([0, 1100, 0, 1100000])
# 修改轴的范围
plt.savefig('squares_plot.png', bbox_inches='tight')
# 自动保存图片 删除多余空白
生成图片如下:
3) 随即漫步
- 创建RandomWalk()类:
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:
# 1,-1 来确定向右还是向左
x_direction = choice([1, -1])
# 0~4 确定走多远
x_distance = choice([0, 1, 2, 3, 4])
# 确定移动的距离
x_step = x_distance * x_direction
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_distance * y_direction
if x_step == 0 and y_step == 0:
continue
# x_step与x_values 中最后一个值相加得到下一个点的X
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)
- 绘制随机漫步:
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
# 生成 50000个随机漫步
rw = RandomWalk(50000)
rw.fill_walk()
# 设置屏幕 分辨率 尺寸
plt.figure(dpi=144, figsize=(10, 6))
# 给点上色
point_number = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values,
c=point_number,
cmap=plt.cm.Blues,
edgecolors='none', s=1)
# 突出起始点绿色 终点 红色
plt.scatter(0, 0, c='green',
edgecolors='none', s=100)
plt.scatter(rw.x_values[-1],
rw.y_values[-1],
c='red', edgecolors='none',
s=100)
# 隐藏坐标轴
# plt.axes().get_xaxis().set_visible(False)
# plt.axes().get_yaxis().set_visible(False)
plt.show()
# 按 Y继续生成,按N退出生成
keep_running = input("Y/N")
if keep_running == 'N':
break
生成图片如下: