从目录中多个CSV文件绘制以时间为X轴的多列数据图表
Solution to Plot CSV Data by Time for All Files in a Directory
Prerequisites
First, make sure you have the right tools installed—we'll use Python with pandas for data handling and matplotlib for plotting. Install them with this command:
pip install pandas matplotlib
Step-by-Step Code Implementation
Here's a complete script that does exactly what you need: it loops through every CSV in your target directory, reads the data, and plots each numeric column against the formatted GMT time (or Unix timestamp, if you prefer).
import os import pandas as pd import matplotlib.pyplot as plt # Replace this with your actual directory path TARGET_DIRECTORY = "./your_csv_folder" # Loop through each file in the directory for file_name in os.listdir(TARGET_DIRECTORY): # Skip non-CSV files if not file_name.endswith(".csv"): continue full_file_path = os.path.join(TARGET_DIRECTORY, file_name) print(f"Generating plots for {file_name}...") # Define column names since your CSVs don't have headers # Adjust this list to match the exact number of columns in your files column_labels = [ "unix_timestamp", "gmt_time", "temp1", "humidity1", "temp2", "humidity2", "count", "ratio", "metric1", "metric2" ] # Load the CSV data into a DataFrame df = pd.read_csv(full_file_path, names=column_labels) # Convert the GMT time string to a proper datetime object # This makes the X-axis labels human-readable instead of raw text df["gmt_time"] = pd.to_datetime(df["gmt_time"]) # Calculate how many numeric columns we have (subtract the two time columns) num_numeric_cols = len(df.columns) - 2 # Create a figure with one subplot per numeric column fig, axes = plt.subplots(num_numeric_cols, 1, figsize=(12, 4*num_numeric_cols), tight_layout=True) fig.suptitle(f"Data from {file_name}", fontsize=16, y=1.02) # Plot each numeric column against GMT time for idx, col in enumerate(df.columns[2:]): # Handle case where there's only one numeric column (axes won't be an array) ax = axes[idx] if num_numeric_cols > 1 else axes # Swap df["gmt_time"] with df["unix_timestamp"] here if you want Unix time as X-axis ax.plot(df["gmt_time"], df[col], linewidth=2, label=col) ax.set_xlabel("GMT Time", fontsize=12) ax.set_ylabel(col, fontsize=12) ax.legend() ax.grid(True, linestyle="--", alpha=0.6) # Uncomment this line to save the plot as a PNG instead of showing it # plt.savefig(f"{file_name}_plot.png", dpi=150, bbox_inches="tight") # Display the plot plt.show() plt.close() # Free up memory after each plot to avoid clutter
Key Customization Tips
- Adjust Column Names: Make sure
column_labelsmatches the exact number of columns in your CSV files. Add or remove entries from this list if your data has more/fewer columns. - Switch to Unix Time: To use the first column (Unix timestamp) as the X-axis, just replace
df["gmt_time"]withdf["unix_timestamp"]in theax.plot()line. - Combine All Columns in One Plot: If you prefer to see all data on a single chart instead of subplots, simplify the plotting section:
fig, ax = plt.subplots(figsize=(12, 8)) for col in df.columns[2:]: ax.plot(df["gmt_time"], df[col], label=col) ax.set_xlabel("GMT Time") ax.set_ylabel("Values") ax.legend() ax.grid(True) - Style Tweaks: You can change line colors, add markers, or use a different theme (like seaborn) to polish your plots. For example, add
import seaborn as sns; sns.set_style("darkgrid")at the top for a cleaner grid.
内容的提问来源于stack exchange,提问作者Sedi
相关产品推荐
相关产品推荐

