RT,小白学习py,个人理解,如有不对希望指正,不胜感激
参考书籍:《Python编程从入门到实践》 Eric Matthes
开始进入第二个模块,进行matplotlib的学习!
1.安装 安装教程超赞
2.绘制折线图
创建一个列表,存储平方数,然后传递给函数plot(),plt.show()打开matplotlib查看器,并且显示绘制的图形
import matplotlib.pyplot as plt
squares=[1,4,9,16,25]
plt.plot(squares)
plt.show()
3.对可视化优化之后的图表
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)
#fontsize是文字尺寸
#设置刻度标记的大小
plt.tick_params(axis='both',labelsize=14)
plt.show()
4.上面的代码 数值是有问题的,4.0的平方对应了25
是因为 给plot()提供一系列数字的时候,它假设第一个数据对应的是X坐标值是0
所以我们可以给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=5)#线条粗细
5.使用scatter()绘制散点图
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()
6.颜色映射
plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Reds,edgecolor='none',s=40)
第三个参数位置,代表了颜色,而颜色随Y增长而增长,再通过第四个参数指定渐变的颜色,实现颜色的由浅到深
7.自动保存图表
plt.savefig('square_plot.png',bbox_inches='tight')
#第一个实参指定以什么样的文件名保存图表,第二个实参指定将图表多余的空白区域裁减掉
8.模拟随机漫步
;类:
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:
#决定前进方向以及沿着个方向前进的距离
x_direction=choice([1,-1])
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)
主函数
import matplotlib.pyplot as plt
from random_walk import RandomWalk
#创建一个randomwalk实例,并将其包含的点都绘制出来
rw=RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()
9.给点着色 根据先后顺序渐变
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=15)