You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取多份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_styles list 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_name parameter adds the CSV filename to the legend, so you can easily match curves to their source files.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:26:33