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

如何在Pandas分组后于单图中绘制多列数据的多折线图

Solution: Plotting 6 Lines (Each Label's value1 & value2)

Got it, let's break this down so you can get all 6 lines on your chart. The key is to iterate through each label group, then plot both value1 and value2 for that group as separate lines. Here's the complete, working code:

import pandas as pd
import datetime
import matplotlib.pyplot as plt

# Create your DataFrame
df = pd.DataFrame( {
    "date": [datetime.datetime(2018, 1, x) for x in range(1, 8)],
    "label": ["A", "A", "B", "B", "C", "A", "C"],
    "value1": [1, 22, 3, 4, 5, 6, 7],
    "value2": [10, 4, 30, 5, 6, 8, 9]
} )
df.set_index('date', inplace=True)

# Set up the plot
fig, ax = plt.subplots(figsize=(10, 6))

# Iterate through each label group and plot both values
for label, group_data in df.groupby('label'):
    # Plot value1 for the current label
    ax.plot(group_data.index, group_data['value1'], 
            label=f'{label} - value1', 
            marker='o',  # Adds circle markers for clarity
            linewidth=2)
    # Plot value2 for the current label
    ax.plot(group_data.index, group_data['value2'], 
            label=f'{label} - value2', 
            marker='s',  # Adds square markers to distinguish from value1
            linewidth=2,
            linestyle='--')  # Dashed line for value2

# Add chart labels and formatting
ax.set_xlabel('Date', fontsize=12)
ax.set_ylabel('Value', fontsize=12)
ax.set_title('Daily Trends: value1 and value2 per Label', fontsize=14)
ax.legend(fontsize=10)  # Shows all 6 line labels
plt.xticks(rotation=45)  # Rotate dates so they don't overlap
plt.tight_layout()  # Adjust layout to fit all elements

plt.show()

How this works:

  • df.groupby('label') splits your data into three separate DataFrames (one for A, B, C)
  • For each group, we plot two lines: one for value1 and one for value2
  • We use unique markers (o for circles, s for squares) and a dashed line for value2 to make the lines easy to tell apart
  • The label parameter in ax.plot() ensures each line gets a unique entry in the legend, so you can identify which line corresponds to which label/value pair

If you want to customize colors further, you can add a color parameter to each ax.plot() call (e.g., color='blue' for A's value1, color='darkblue' for A's value2).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:15:09