关于python制成随机散点图和正态散点图_matplotlib_numpy_
题记:最近和小伙伴在准备美赛(美国大学生数学建模比赛),筹备D题(运筹题)时遇到要建立正态分布散点图(模拟人群),于是开始用python_matplotlib包来做(立志用python+matplotlib来代替matlab >_<)
参考内容:
numpy.random.randn()用法——周正己
Python 二维列表与一维列表的互相转化——Yolandera
numpy.random.uniform介绍——ma_studd
Python3 SciPy解常微分方程 用Matplotlib演示
数值 Python: 常微分方程【GreatX’s Blog】
- 下面po出我的代码
随机分布散点图
#以下代码为:生成随机散点图
import matplotlib.pyplot as plt
import numpy as np
def rand_data():
return np.random.uniform(low=0., high=3., size=(100,))
x1, y1 = [rand_data() for i in range(2)]
plt.plot(x1,y1, 'o',color='b')
plt.show()
结果:【注意:因为是随机分布所以每次都不一样】
正态分布散点图
#以下代码为生成正态分布散点图
#PS:代码中有一些print(xxx)可以让读者知道输出的量是什么
import matplotlib.pyplot as plt #引入matplotlib中的画图包
import numpy as np #引入Numpy
#mu, sigma = 10, 10 #有关于正态分布的值μ,σ
def random_randomn(): #创建一个包含建立正态分布函数的random_randomn()函数
return np.random.randn(1,10000)
#x2 = np.random.randn(1,6)
for i in range(1): #在这个循环中,把函数random_randomn()得出的正态分布的10000个数值放到x2中,注意,这里x2是一个【二维数组】:[[xxx,xxx,xxx]]后面要变成一维才能被plt读取
x2 = random_randomn()
#print(i)
#print(x2)
x2 = ([i for item in x2 for i in item])#在这个循环中我们能把二维的数组转换成一维的数组,y2同理
#print(x2)
#y2 = np.random.randn(1,6)
for i in range(1):
y2 = random_randomn()
#print(i)
#print (y2)
y2 = ([i for item in y2 for i in item])
#print(y2)
plt.plot(x2,y2, 'o',color='b')#画出散点图
plt.show()
最终结果:
10000个点的情况:
1000个点的情况: