目录
15.2.3 使2散点图并设置其样式
import matplotlib.pyplot as plt
plt.scatter(2, 4)
plt.show()
import matplotlib.pyplot as plt
plt.scatter(2, 4, s=200)
# 设置图表标题并给坐标轴加上标签
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.show()
15.2.4 使用 scatter()绘制一系列点
import matplotlib.pyplot as plt
x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]
plt.scatter(x_values, y_values, s=100)
# 设置图表标题并给坐标轴指定标签
--snip--
15.2.5 自动计算数据
import matplotlib.pyplot as plt
1 x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
2 plt.scatter(x_values, y_values, s=40)
# 设置图表标题并给坐标轴加上标签
--snip--
# 设置每个坐标轴的取值范围
3 plt.axis([0, 1100, 0, 1100000])
plt.show()
15.2.6 删除数据点的轮廓
plt.scatter(x_values, y_values, edgecolor='none', s=40)
15.2.7 自定义颜色
plt.scatter(x_values, y_values, c='red', edgecolor='none', s=40)
plt.scatter(x_values, y_values, c=(0, 0, 0.8), edgecolor='none', s=40)
15.2.8 使用颜色映射
import matplotlib.pyplot as plt
x_values = list(range(1001))
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues,
edgecolor='none', s=40)
# 设置图表标题并给坐标轴加上标签
--snip--
注意
要了解pyplot中所有的颜色映射,请访问http://matplotlib.org/,单击Examples,向下滚动 到Color Examples,再单击colormaps_reference。
15.2.9 自动保存图表
plt.savefig('squares_plot.png', bbox_inches='tight')
15.3 随机漫步
15.3.1 创建 RandomWalk()类
1 from random import choice
class RandomWalk():
"""一个生成随机漫步数据的类"""
2 def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
self.num_points = num_points
# 所有随机漫步都始于(0, 0)
3 self.x_values = [0]
self.y_values = [0]
15.3.2 选择方向
def fill_walk(self):
"""计算随机漫步包含的所有点"""
# 不断漫步,直到列表达到指定的长度
1 while len(self.x_values) < self.num_points:
# 决定前进方向以及沿这个方向前进的距离
2 x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
3 x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
4 y_step = y_direction * y_distance
# 拒绝原地踏步
5 if x_step == 0 and y_step == 0:
continue
# 计算下一个点的x和y值
6 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)
15.3.3 绘制随机漫步图
import matplotlib.pyplot as plt
from random_walk import RandomWalk
# 创建一个RandomWalk实例,并将其包含的点都绘制出来
1 rw = RandomWalk()
rw.fill_walk()
2 plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
关于“Python”的核心知识点整理大全37-CSDN博客
关于“Python”的核心知识点整理大全25-CSDN博客
关于“Python”的核心知识点整理大全12-CSDN博客