【发布时间】:2014-01-31 13:17:09
【问题描述】:
我的想法是尝试生成随机数据点(2D、x 和 y 坐标),这些数据点彼此靠近,模仿以下场景:
- 我选择例如1个对象10分。
- 一个数据库中有 200 个这样的对象。
- 我记录了所有对象上相同位置的 10 个点的坐标。所以我的数据由 200x10 行组成,所以前 10 行表示在第一个对象上采样的 10 个点的坐标,接下来的 10 行表示第二个对象上的相同点,依此类推。
对象中的点集合在散点图中应靠近,但它们不应完全相同或相距太远。现在如果我使用普通的随机生成器,大多数时候我会得到很多均匀分布的随机点......
这是我尝试使用 numpy、pandas 和 matplotlib 的过程,以及来自 this 帖子的多变量法线的酷用法。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import brewer2mpl as bmpl
#the part of the code I use for generating correlated ranges for points
#but I have used it for generating x,y coords as well but it didn`t work out
corr = 0.95
means = [200, 180]
stds = [10, 10]
covs = [[stds[0]**2, stds[0]*stds[1]*corr],[stds[0]*stds[1]*corr, stds[1]**2]]
coordstest = np.random.multivariate_normal(means, covs, 20)
#now the part for generating x and y coords
coords1x = np.random.uniform(coordstest[0,0], coordstest[0,1], 200)
coords1y = np.random.uniform(coordstest[1,0], coordstest[1,1], 200)
coords2x = np.random.uniform(coordstest[2,0], coordstest[2,1], 200)
coords2y = np.random.uniform(coordstest[3,0], coordstest[3,1], 200)
... up to 10
#them make them into two-column arrays
coords1 = np.vstack((coords1x, coords1y)).T
coords2 = np.vstack((coords2x, coords2y)).T
... up to 10
#and generate individual levels
individuals = np.arange(0,200) #generate individual levels
individuals = np.tile(individuals, 10)
individuals = pd.Series(individuals)
#finally generate pandas data frame and plot the results
allCoords = np.concatenate((coords1, coords2, coords3, coords4, coords5, coords6, coords7, coords8, coords9, coords10))
allCoords = pd.DataFrame(allCoords)
allCoords.columns = ['x','y']
allCoords['individuals'] = individuals
allCoords['index'] = allCoords.index.tolist()
allCoords = allCoords.sort_index(by=['individuals', 'index'])
del allCoords['index']
allCoords = allCoords.set_index(np.arange(0,2000))
plt.scatter(allCoords['x'], allCoords['y'], c = allCoords['individuals'], s = 40, cmap = 'hot')
这是散点
并且相同颜色的点应该在本地分组。有什么想法可以实现吗?
【问题讨论】:
标签: python random numpy matplotlib pandas