Pylab中的散点图:排列轴和数据
我正在尝试使用pylab制作一个散点图,但到目前为止我一直失败得很惨。我并不是专业程序员,所以请多多包涵。
我有一个数据集,里面有两列数据,存储在一个大约有6万行的csv文件里。这里有个样本:
100000000012640,0.888888888888889
100000000105442,0.777777777777778
100000000206866,1.0
100000000304930,0.777777777777778
100000000583236,0.888888888888889
100000000683528,0.777777777777778
718435316,1.0
718494043,0.777777777777778
718602951,0.777777777777778
718660499,0.777777777777778
718766852,1.0
718795104,1.0
718862926,0.777777777777778
718927526,0.777777777777778
718952836,1.0
719102865,0.777777777777778
719156726,1.0
719213511,1.0
719425334,1.0
719452158,1.0
719493947,0.777777777777778
719566609,1.0
720090346,0.777777777777778
720127760,0.777777777777778
720143948,0.944444444444444
720221566,1.0
720256688,0.944444444444444
720349817,0.777777777777778
720380601,0.777777777777778
720446322,1.0
720524740,1.0
720560353,1.0
720594066,0.777777777777778
720673388,1.0
720716865,0.777777777777778
720730249,1.0
720774433,1.0
我的目标是绘制这个数据的散点图,第一列数据放在x轴上,第二列数据放在y轴上。x轴的值是按从大到小的顺序排列的,起始值是样本中的值,结束值是999963505。y轴的值总是在0到1之间。
这是我尝试过的(使用“ipython --pylab”):
data = loadtxt('./data/OD-4322/facebookID.csv', unpack=True, dtype=('float', 'float'), delimiter=',')
scatter(data[0],data[1])
这样得到的图看起来像个散点图,但并不是我想要的样子:
(我本来想直接发图,但因为我在这个网站的信誉不够,所以不能这样做)。
我该怎么做才能让x轴的范围和我的值一致呢?为什么我图中的点都堆在0和1上,而实际上它们在0到1之间是分散的呢?
1 个回答
1
Pylab 是一个使用 numpy 的工具,你可以在这里查看提供的数据格式 这里。你在第一列使用了非常大的数字,并且不需要双精度浮点数,而是需要高精度的整数值。看看你粘贴的示例数据:
>>> x = np.loadtxt('./temp.dat', unpack=True, dtype=('float'), delimiter=',')[0]
>>> x
array([ 1.00000000e+14, 1.00000000e+14, 1.00000000e+14,
1.00000000e+14, 1.00000001e+14, 1.00000001e+14])
>>> x = np.loadtxt('./temp.dat', unpack=True, dtype=('uint64'), delimiter=',')[0]
>>> x
array([100000000012640, 100000000105442, 100000000206866, 100000000304930,
100000000583236, 100000000683528], dtype=uint64)
>>> y = np.loadtxt('./temp.dat', unpack=True, dtype=('float'), delimiter=',')[1]
>>> scatter(x,y)
注意,你在代码 scatter(data[0],data[1])
中所做的事情,是在 loadtxt()
语句之后进行的,针对这两列数据。第一个函数会在读取数据后将其显示为浮点数。使用 `uint64` 格式读取的数据会对你的散点图有帮助。
一个很好的起点是: matplotlib 画廊
为了回应你的评论,关于如何更好地控制输入数据的读取:
# create python lists to store the data
x_vals = []
y_vals = []
#open file and read in a list containing all lines as string
f = open("./temp.dat","r")
lines = f.readlines()
#Go through the lines
#strip() takes away "\n" characters and such
#split(",") creates a list of the string line splitted into (here: 2) substrings
for line in lines:
x,y = line.strip().split(",")
#append values to their lists and apply the right format
x_vals.append(np.uint64(x))
y_vals.append(np.float64(y))
scatter(x_vals,y_vals)
#or just plot the data as points using:
plot(x_vals,y_vals,"o")
你的数据在最小值和最大值之间的范围非常大, 当你将数据集分成小数字和大数字时,结果会更好。