[英]How can I read multiple csv files from a single directory and graph them separately in Python?
I want to read csv files from a directory and plot them and be able to click the arrow button to step through a plot and look at a different plot. 我想从目录中读取csv文件并绘制它们,并能够单击箭头按钮逐步浏览绘图并查看不同的绘图。 I want to specify which column and be able to title it as well as I have in the code below as well. 我想指定哪个列,并且能够在下面的代码中标注它。
I am able to read the csv file and plot a single plot with specific columns but I am not sure how to do it with multiple. 我能够读取csv文件并绘制具有特定列的单个图,但我不知道如何使用多个。 I've tried glob but it didn't work, I do not want to concatenate them to a single csv file. 我已经尝试了glob但是它不起作用,我不想将它们连接到单个csv文件。 I have provided my code below. 我在下面提供了我的代码。 Any help would be appreciated. 任何帮助,将不胜感激。 Thank you. 谢谢。
import pandas as pd
import matplotlib.pyplot as plt
cols_in = [1, 3]
col_name = ['Time (s), Band (mb)']
df = pd.read_csv("/user/Desktop/TestNum1.csv", usecols = cols_in, names =
col_name, header = None)
fig, ax = plt.subplots()
my_scatter_plot = ax.scatter(df["Time (s)"], df["Band (mb)"])
ax.set_xlabel("Time (s)")
ax.set_ylabel("Band (mb)")
ax.set_title("TestNum1")
plt.show()
You just need to add a for
loop over all the files and use glob
to collect them. 您只需要在所有文件上添加for
循环并使用glob
来收集它们。
For example, 例如,
import pandas as pd
import matplotlib.pyplot as plt
import glob
cols_in = [1, 3]
col_name = ['Time (s), Band (mb)']
# Select all CSV files on Desktop
files = glob.glob("/user/Desktop/*.csv")
for file in files:
df = pd.read_csv(file, usecols = cols_in, names =
col_name, header = None)
fig, ax = plt.subplots()
my_scatter_plot = ax.scatter(df["Time (s)"], df["Band (mb)"])
ax.set_xlabel("Time (s)")
ax.set_ylabel("Band (mb)")
ax.set_title("TestNum1")
plt.show()
Keeping plt.show()
inside the for
loop will ensure each plot is plotted. 在for
循环中保持plt.show()
将确保绘制每个绘图。 It should be pretty easy to search for 'How to add a title to a plot in python' for answers to your other questions. 搜索“如何为python中的绘图添加标题”应该很容易找到其他问题的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.