基于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
templateDataFrame, which lets us pair eachwell_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_idfrom yourdDataFrame, 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
相关产品推荐
相关产品推荐

