使用Excel表格中的数据来绘制python图表

所以我有很多数据在Excel电子表格中。 我需要通过python来绘制。 我知道如何使用xlrd从excel文件中读取数据,我知道如何使用matplotlib在python中绘制graphics。 基本上我的数据看起来有x坐标,y坐标,正和负y错误的列。 我需要一种方法来将数据从电子表格导入,并成为graphics上的点和误差线。 说实话,我是非常新的python,不知道为什么我的代码不工作。

import xlrd import numpy as np import matplotlib.pyplot as plt file_location = "C:/Users/Rima/Desktop/apjl731data.xlsx" workbook = xlrd.open_workbook(file_location) first_sheet = workbook.sheet_by_index(0) for col in range(first_sheet.ncols): x = first_sheet.cell_value(0,col) y = first_sheet.cell_value(1,col) yerr = first_sheet.cell_value(2,col) plt.errorbar(x,y,yerr,fmt='r^') plt.show() 

我还没有find如何做到这一点在线,只有如何使用python在Excel中的graphics。 我敢肯定我的代码可能缺less了很多,如果工作,但我不知道是什么。 对于yerr来说,为了在数据点的顶部和底部得到不同的错误值,我将它作为yerr = np.array([])作为数组传递给每个点。 我不知道如何导入数据,因为我的积极的错误和负面的错误是在电子表格的不同列。 如果有人知道如何导入数据请帮助,因为这将使我的生活更轻松,因为我不必手型50数据点。 谢谢!

编辑:我的数据将是一个例子

log(O/H)+12 positive error negative error virgo infall distance 8.56 0.05 0.05 4.61 8.59 0.03 0.03 - 8.54 0.04 0.06 2.97297 8.94 0.13 0.12 8.24493

我的数据里有空白,用 – 标记,我不知道在试图绘制时是否会造成错误。 所以我可能需要一种方法来跳过这些行。 再次感谢。

编辑2:我仍然有一个错误,所以这里是回溯。 在这里输入图像说明

谢谢!

我做了一些假设。 假设你的数据是这样的:

 xy yerr_positive yerr_negative 1 1 0.1 0.2 2 2 0.1 0.2 3 3 0.1 0.2 4 4 0.1 0.2 

我还修改了如何轻微加载数据,以便将每列加载到它自己的数组中,例如:

 x = [first_sheet.cell_value(i, 0) for i in range(first_sheet.ncols)] 

您可以通过传递一个表单的数组来使用errorbar对于一个值具有正数+负数的错误:

 yerr = [y_error_negative, y_error_positive] 

y_error_negativey_error_positive是与y长度相同的数组。

你应该有以下几点:

 import xlrd import numpy as np import matplotlib.pyplot as plt file_location = "C:/Users/Rima/Desktop/apjl731data.xlsx" workbook = xlrd.open_workbook(file_location) first_sheet = workbook.sheet_by_index(0) x = [first_sheet.cell_value(i, 0) for i in range(first_sheet.ncols)] y = [first_sheet.cell_value(i, 1) for i in range(first_sheet.ncols)] yerr_pos = [first_sheet.cell_value(i, 2) for i in range(first_sheet.ncols)] yerr_neg = [first_sheet.cell_value(i, 3) for i in range(first_sheet.ncols)] yerr = [yerr_neg, yerr_pos] plt.errorbar(x,y,yerr,fmt='r^') plt.axis([0,5,0,5]) plt.show() 

这给出了这个: 在这里输入图像说明

没有更多的细节就难以回答。

编辑:

如果你在数据中有“ – ”,有很多方法可以忽略它。 所以,用上面概述的方法快速破解,你可以重新检查x值:

 xy yerr_positive yerr_negative 1 1 0.1 0.2 - 2 0.1 0.2 3 3 0.1 0.2 4 4 0.1 0.2 

然后,您将删除“ – ”并replace为0,例如,

 x = [float(i) if i != '-' else 0 for i in x] 

另一种方法是在加载时循环值, value if value.isdigit() else 0 ,则不做两个列表value if value.isdigit() else 0

或者,你可以像你说的那样完全忽略它:

 x = [float(i) for i in x if i!= '-'] 

如果在处女座的入侵距离上可以有一些通用的上限,那么更好的办法是不浪费你的金属性数据。 如果您不断收到TypeErrors,请提供更多信息。