您的位置:首页 > 编程语言 > PHP开发

matplotlib可视化及一例《随机漫步》

2020-07-14 06:11 83 查看
import matplotlib.pyplot as plt

x = list(range(1,1001))
y = [i**2 for i in x]

plt.scatter(x,y,s=40) #点的大小
#设置标题,并给坐标轴设置标签
plt.title('Square Numbers',fontsize=24)
plt.xlabel('Value',fontsize=14)
plt.ylabel('Square of Value',fontsize=14)

#设置坐标轴的取值范围,axis()函数要求输入四个数,x轴y轴的最小值和最大值.
plt.axis([0,1100, 0,1100000])

plt.show()

#我们会发现点连在一起了,去掉数据点的轮廓,edgecolor='none'.
plt.scatter(x, y, s=10, c='red',  #c设置点的颜色.还可以传入元组,(R,G,B) 取值0~1
edgecolor='none')  #用这句替换上面对应的语句

plt.scatter(x, y, s=10, c=(0, 0, 0.8),  #c设置点的颜色.还可以传入元组,(R,G,B) 取值0~1
edgecolor='none')

颜色映射

x = list(range(1,1001))
y = [i**2 for i in x]

plt.scatter(x,y,s=40,c=y,
cmap = plt.cm.Blues,  #先用c设置一个颜色列表,再使用cmap哪个颜色映射
edgecolor='none'
)
#设置标题,并给坐标轴设置标签
plt.title('Square Numbers',fontsize=24)
plt.xlabel('Value',fontsize=14)
plt.ylabel('Square of Value',fontsize=14)

#设置坐标轴的取值范围,axis()函数要求输入四个数,x轴y轴的最小值和最大值.
plt.axis([0,1100, 0,1100000])

# plt.show()

#savefig保存并显示图片,可用参数bbox_inches='tight' 减去图表空白区域.
plt.savefig('square_plot.jpg')

例1:彩色立方

#彩色立方
x = list(range(1,5001))
y = [i*i*i for i in x]

plt.scatter(x, y, s=20, c=y, cmap=plt.cm.Blues, edgecolor='none')
plt.show()

例2:随机漫步

#随机漫步
from random import choice
import matplotlib.pyplot as plt

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_work(self):
'''计算随机漫步包含的所有点'''

while len(self.x_values) < self.num_points:

#确定点的方向以及每次漫步距离
x_dire = choice([1,-1])
x_dist = choice([0,1,2,3,4])
x_step = x_dire * x_dist

y_dire = choice([1,-1])
y_dist = choice([0,1,2,3,4])
y_step = y_dire * y_dist

#拒绝原地踏步
if x_step == 0 and y_step == 0:
continue

#确定下一个点的位置
x_new = self.x_values[-1] + x_step
y_new = self.y_values[-1] + y_step

self.x_values.append(x_new)
self.y_values.append(y_new)

#创建一个实例
rw = RandomWalk()
rw.fill_work()
plt.scatter(rw.x_values, rw.y_values, s=10)
plt.show()

#模拟多次随机漫步
while True:
rw = RandomWalk(50000)
rw.fill_work()

#设置绘图窗口的尺寸,dpi分辨率.
plt.figure(dpi=128,figsize=(10,6))
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, s=1,
c=point_numbers, cmap=plt.cm.Blues,  #以颜色深浅来分辨绘制点的顺序.
edgecolors='none')

#突出起点和终点
plt.scatter(0, 0, c='green', edgecolor='none', s=80)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red',
edgecolor='none', s=80)

#隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

plt.show();

keep_running = input('Make another walk? (y/n)')
if keep_running =='n':
break

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: