【发布时间】:2016-11-07 16:37:51
【问题描述】:
我正在尝试创建一个 python 脚本,该脚本读取一个 CSV 文件,该文件包含按第一行中的示例名称排列的数据以及每个名称下方的数据,如下所示:
sample1,sample2,sample3
343.323,234.123,312.544
我试图从数据集中将每个样本的累积分布函数绘制到同一轴上。使用下面的代码:
import matplotlib.pyplot as plt
import numpy as np
import csv
def isfloat(value):
'''make sure sample values are floats
(problem with different number of values per sample)'''
try:
float(value)
return True
except ValueError:
return False
def createCDFs (dataset):
'''create a dictionary with sample name as key and data for each
sample as one list per key'''
dataset = dataset
num_headers = len(list(dataset))
dict_CDF = {}
for a in dataset.keys():
dict_CDF["{}".format(a)]= 1. * np.arange(len(dataset[a])) / (len(dataset[a]) - 1)
return dict_CDF
def getdata ():
'''retrieve data from a CSV file - file must have sample names in first row
and data below'''
with open('file.csv') as csvfile:
reader = csv.DictReader(csvfile, delimiter = ',' )
#create a dict that has sample names as key and associated ages as lists
dataset = {}
for row in reader:
for column, value in row.iteritems():
if isfloat(value):
dataset.setdefault(column, []).append(value)
else:
break
return dataset
x = getdata()
y = createCDFs(x)
#plot data
for i in x.keys():
ax1 = plt.subplot(1,1,1)
ax1.plot(x[i],y[i],label=str(i))
plt.legend(loc='upper left')
plt.show()
这给出了下面的输出,它只正确显示了其中一个示例(图 1A 中的示例 1)。
Figure 1A. Only one CDF is displaying correctly (Sample1). B. Expected output
每个样本的值数量不同,我认为这就是我的问题所在。
这一直困扰着我,因为我认为解决方案应该相当简单。任何帮助/建议都会有所帮助。我只是想知道如何正确显示数据。数据可以在here找到。预期输出如图 1B 所示。
【问题讨论】:
-
sample2 和 3 的预期 cdf 是多少?
-
我添加了 Excel 中生成的预期输出图像
-
我还是只能看到上一张图,应该不止一个链接吗?
-
道歉。修好了。
-
我猜你没有从 CSV 读取所有数据,检查 x.shape 看看它是你所期望的。
标签: python numpy matplotlib cumulative-sum