【发布时间】:2021-04-12 15:54:09
【问题描述】:
我已经编写了绘图函数和正文部分,但无法找出获取数据 csv 的必要代码。所以基本上我的代码是:
import random
import matplotlib.pyplot as plt
def get_data_csv(fn, colx, coly, sep=','):
return x_data, y_data, x_label, y_label
def plot_graphs(x_data, y_data, x_label, y_label, title, color=None):
plt.figure()
#if there are more than one graph to plot in the same figure, same x-axis
if all(type(arg) == list for arg in [x_data, y_data, y_label]):
lx = len(x_data)
if lx > 1 and all(len(arg) == lx for arg in [y_data, y_label]):
for i in range(lx):
color = list(random.random() for c in range(3))
plt.plot(x_data[i], y_data[i], color = color, label = y_label[i])
plt.xlabel(x_label)
plt.title(title)
plt.legend()
else:
print('Something get wrong, review your arguments')
# if there is only one graph to plot
else:
plt.plot(x_data, y_data, color=color)
plt.ylabel(y_label)
plt.xlabel(x_label)
plt.title(title)
plt.xlim([min(x_data), max(x_data)])
plt.grid('all')
plt.show()
if __name__ == "__main__":
user_fn = input("Enter CSV filename(s), separated by ',': ")
user_colx = input("Enter respective x-column(s), separated by ',': ")
user_coly = input("Enter respective y-column(s), separated by ',': ")
user_title = input("Enter title: ")
fn = user_fn.split(',')
colx = list(int(c) for c in user_colx.split(','))
coly = list(int(c) for c in user_coly.split(','))
if len(fn) == 1:
fn = fn[0]
x_data, y_data, x_label, y_label = get_data_csv(fn, colx[0], coly[0])
else:
x_data, y_data, y_label = [], [], []
for i in range(len(fn)):
auxx, auxy, x_label, auxylbl = get_data_csv(fn[i], colx[i], coly[i])
x_data.append(auxx)
y_data.append(auxy)
y_label.append(auxylbl)
plot_graphs(x_data, y_data, x_label, y_label, user_title, color='black')
如您所见,我无法编写 def get_data_csv 部分。我认为我应该使用 readline() 从文件中获取标题行,之后,我可以使用任何方式获取其他信息
举例说明代码应该如何工作。
Enter CSV filename(s), separated by ',': sinusoid.csv
Enter respective x-column(s), separated by ',': 0
Enter respective y-column(s), separated by ',': 1
Enter title: Sine
这应该可以。我需要帮助
【问题讨论】:
-
你应该看看
pandas,它有一个read_csv函数可以将csv文件读入一个与matplotlib配合得很好的数据帧。
标签: python python-3.x csv matplotlib plot