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

基于Matplotlib批量绘制单折线图并自动添加样本标签

Solution to Plot Individual Line Charts with Automatic Sample Labels

Let's fix this issue so you get a separate line chart for each sample, with the correct label pulled automatically from your template data. The problem with your original code is that you're trying to plot all columns at once and passing an entire Series to the label parameter, which doesn't map each line to its specific sample name.

Here's the corrected approach:

import pandas as pd
import matplotlib.pyplot as plt

# Your original data
d = pd.DataFrame({'Time_min': [1, 2, 3], 'A1': [1000, 2000, 1000], 'A12': [2000, 3000, 2000], 'B12': [3000, 5000, 3000]})
template = pd.DataFrame({'well_id': ['A1', 'A12', 'B12'], 'name': ['Sample1', 'Sample2', 'Sample4']})

# Iterate over each row in the template to match well_id with sample name
for _, row in template.iterrows():
    well_id = row['well_id']
    sample_name = row['name']
    
    # Create a new figure for each sample
    plt.figure()
    # Plot the specific well's data against Time_min, using the sample name as label
    plt.plot(d['Time_min'], d[well_id], label=sample_name)
    
    # Add plot details for clarity
    plt.title(f'Line Chart for {sample_name}')
    plt.xlabel('Time (min)')
    plt.ylabel('Value')
    plt.legend()
    plt.show()

Why this works:

  • We loop through each entry in the template DataFrame, which lets us pair each well_id (like 'A1') with its corresponding sample name (like 'Sample1') directly.
  • For every sample, we create a new plt.figure() so each line gets its own separate chart.
  • We explicitly plot only the column matching the current well_id from your d DataFrame, and set the label to the sample's name—this ensures the legend always matches the line being plotted.

If you prefer using the merged df1 instead of template, you can adjust the loop to iterate over df1 instead (the logic stays the same):

for _, row in df1.iterrows():
    well_id = row['well_id']
    sample_name = row['name']
    
    plt.figure()
    plt.plot(d['Time_min'], d[well_id], label=sample_name)
    plt.title(f'Line Chart for {sample_name}')
    plt.xlabel('Time (min)')
    plt.ylabel('Value')
    plt.legend()
    plt.show()

This approach eliminates the need to manually specify each sample and label—everything is mapped automatically from your template data.

内容的提问来源于stack exchange,提问作者Olka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 12:57:43