如何读取多份CSV文件并在同一Matplotlib图中绘制多条曲线?
Plot Multiple CSV Curves in One Figure with Python (Like
xmgrace -free -nxy *) Got it, let's adapt your existing matplotlib script to replicate that handy xmgrace workflow! Here's a modified version that reads all your CSV files and plots them on the same axes, with clear labeling so you can tell each curve apart:
Full Modified Script
import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter import glob # Initialize the figure and axes (matches your original setup) plt.figure(figsize=(9,6)) ax = plt.subplot(111) ax.yaxis.set_major_formatter(FormatStrFormatter('%.4f')) # Grab all CSV files in the current directory (replaces the `*` in your xmgrace command) csv_files = glob.glob('*.csv') # Optional: Define distinct styles for each curve to avoid confusion curve_styles = [ {'color': 'blue', 'linestyle': 'dashdot', 'marker': 'o', 'markerfacecolor': 'red'}, {'color': 'darkgreen', 'linestyle': 'solid', 'marker': 's', 'markerfacecolor': 'yellow'}, {'color': 'orange', 'linestyle': 'dashed', 'marker': '^', 'markerfacecolor': 'cyan'}, # Add more styles if you have more CSV files ] # Loop through each CSV and plot its data for idx, file_name in enumerate(csv_files): with open(file_name) as f: # Reuse your original data cleaning/parsing logic clean_lines = [line.strip() for line in f if line.strip()] data_points = [tuple(map(float, line.split())) for line in clean_lines] x_vals = [point[0] for point in data_points] y_vals = [point[1] for point in data_points] # Apply a style (cycle through our list if more files than styles) current_style = curve_styles[idx % len(curve_styles)] ax.plot(x_vals, y_vals, linewidth=2, markeredgecolor='black', markeredgewidth=2, markersize=6, label=file_name, **current_style) # Add a legend to identify which curve belongs to which CSV ax.legend() # Optional: Add axis labels and a title for clarity (tweak or remove as needed) ax.set_xlabel('X Coordinate') ax.set_ylabel('Y Coordinate') ax.set_title('All CSV Curves Combined') plt.show()
Key Changes & Explanations
glob.glob('*.csv'): This does the same job as the*in your xmgrace command—it automatically finds all CSV files in your working directory, so you don't have to list them manually.- Loop-based plotting: We reuse your existing data parsing code, but run it for every CSV file, plotting each dataset on the same axes object (
ax). - Styling & legends:
- The
curve_styleslist gives each curve a unique look (adjust colors, markers, or linestyles to your preference). If you have more files than styles, it cycles through the list. - The
label=file_nameparameter adds the CSV filename to the legend, so you can easily match curves to their source files.
- The
- Flexibility: Unlike xmgrace, you can fully customize every part of the plot—from axis formatting to marker sizes—directly in the script.
If you want a simpler approach (letting matplotlib auto-pick styles), you can remove the curve_styles list and use this simplified plot call:
ax.plot(x_vals, y_vals, linewidth=2, marker='o', markeredgecolor='black', label=file_name)
Matplotlib will automatically cycle through a default set of colors for each curve.
内容的提问来源于stack exchange,提问作者Hamza allal
相关产品推荐
相关产品推荐

