1.绘制简单的折线图
import matplotlib.pyplot as plt
squares = [1, 4, 9, 16, 25]
plt.plot(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) #设置刻度的样式
plt.show()
1.1 校正图形
当你向plot()提供一系列数字时,它假设第一个数据点对应的x坐标值为0,但我们的第一个
点对应的x值为1
input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.plot(input_values, squares, linewidth=5)
1.2 散点图
import matplotlib.pyplot as plt
x_values = list(range(1,1001))
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, 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]) #坐标轴取值范围
plt.show()
# 删除数据轮廓
plt.scatter(x_values, y_values, edgecolor='none', s=40)
# 自定义颜色
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)
# 颜色映射
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolor='none', s=40)
# 保存
plt.savefig('squares_plot.png', bbox_inches='tight')
2. 随机漫步
2.1创建RandomWalk()类
while len(self.x_values) < self.num_points:
x_direction = choice([1,-1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
2.2设置随机漫步图的样式
使用颜色映射来指出漫步中各点的先后顺序,并删除每个点的黑色轮廓,让它们的颜色更明显
【参考cmap使用:
https://blog.csdn.net/lly1122334/article/details/88535217】
#窗口尺寸
plt.figure(figsize=(10,6))
#range()生成了一个数字列表,其中包含的数字个数与漫步包含的点数相同
point_numbers = list(range(rw.num_points))
#着色
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap='Blues', edgecolor='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.show()
#隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
3. 使用Pygal模拟掷骰子
3.1 创建Die类
return randint(1, self.num_sides)
掷骰子
for roll_num in range(100):
result = die.roll()
results.append(result)