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

如何为Pandas DataFrame分组绘图的X轴添加多标签?附测试进度需求

Hey there! Let's work through your test progress plotting needs step by step. You want to group your DataFrame by Project ID, Release Name, and Cycle Name, plot cumulative test metrics over execution dates, and add meaningful multi-part labels to your X-axis. Here's a practical, code-driven solution:

Step 1: Prep Your Data (if you haven't already)

First, make sure your date column is properly formatted, and your cumulative metrics are calculated per group. If you haven't done this yet, here's how:

import pandas as pd
import matplotlib.pyplot as plt

# Load your DataFrame (replace with your actual data loading logic)
df = pd.read_excel("your_test_data.xlsx")

# Convert execution date to datetime (critical for proper plotting)
df["Test Execution Date"] = pd.to_datetime(df["Test Execution Date"])

# Sort data to ensure cumulative counts are calculated in order
df_sorted = df.sort_values(["Project ID", "Release Name", "Cycle Name", "Test Execution Date"])

# Calculate cumulative tested/passed per group
df_sorted["Cumulative Tested"] = df_sorted.groupby(["Project ID", "Release Name", "Cycle Name"])["Test Count"].cumsum()
df_sorted["Cumulative Passed"] = df_sorted.groupby(["Project ID", "Release Name", "Cycle Name"])["Pass Count"].cumsum()

Step 2: Group and Plot with Clear X-axis/Group Labels

The most readable approach is to create a subplot for each group, where we tie the group's identity directly to the plot (either as a title or extended X-axis label). Here's how:

# Group the sorted data by your three keys
grouped = df_sorted.groupby(["Project ID", "Release Name", "Cycle Name"])

# Set up subplot grid (adjust cols/rows based on your number of groups)
num_groups = len(grouped)
cols = 2
rows = (num_groups + cols - 1) // cols  # Calculate rows needed

fig, axes = plt.subplots(rows, cols, figsize=(16, 6*rows))
axes = axes.flatten()  # Flatten to 1D array for easy iteration

# Iterate through each group and plot
for idx, ((proj_id, release, cycle), group_data) in enumerate(grouped):
    ax = axes[idx]
    
    # Plot the two cumulative metrics
    ax.plot(group_data["Test Execution Date"], group_data["Cumulative Tested"], 
            label="Cumulative Tested", marker="o", linewidth=2)
    ax.plot(group_data["Test Execution Date"], group_data["Cumulative Passed"], 
            label="Cumulative Passed", marker="s", linewidth=2)
    
    # Add group info as a clear title (this is the most intuitive way to link plot to group)
    ax.set_title(f"Project: {proj_id}\nRelease: {release} | Test Cycle: {cycle}", 
                 fontweight="bold", fontsize=12)
    
    # Customize X-axis: format dates and add group context below the axis label
    ax.set_xlabel(f"Test Execution Date\nGroup: {proj_id} - {release} - {cycle}", 
                  fontsize=10)
    ax.tick_params(axis="x", rotation=45, labelsize=9)
    
    # Add legend and subtle grid for readability
    ax.legend()
    ax.grid(alpha=0.3, linestyle="--")

# Hide any empty subplots if your group count doesn't fill the grid
for idx in range(num_groups, len(axes)):
    axes[idx].axis("off")

plt.tight_layout(pad=3.0)
plt.show()

Step 3: Advanced: Adding Multi-Part Labels Directly to X-axis Ticks

If you want to show group info directly on the X-axis ticks (instead of using subplot titles), you can create multi-line tick labels that include both the execution date and the associated group details. Here's an example for a single plot (or adapt it for subplots):

fig, ax = plt.subplots(figsize=(14, 7))

# Plot each group with unique styling
for (proj_id, release, cycle), group_data in grouped:
    ax.plot(group_data["Test Execution Date"], group_data["Cumulative Tested"], 
            label=f"Tested - {proj_id}/{release}/{cycle}", marker="o")
    ax.plot(group_data["Test Execution Date"], group_data["Cumulative Passed"], 
            label=f"Passed - {proj_id}/{release}/{cycle}", marker="s")

# Create multi-line X-tick labels
xticks = ax.get_xticks()
custom_labels = []
for tick_val in xticks:
    # Convert matplotlib's numeric date back to datetime
    date = pd.to_datetime(tick_val, unit="D")
    # Find all groups active on this date
    groups_on_date = df_sorted[df_sorted["Test Execution Date"] == date][["Project ID", "Release Name", "Cycle Name"]].drop_duplicates()
    # Build multi-line label: date + group info
    label_text = date.strftime("%Y-%m-%d") + "\n" + "\n".join([f"{p}/{r}/{c}" for p,r,c in groups_on_date.values])
    custom_labels.append(label_text)

# Update X-axis ticks with custom multi-line labels
ax.set_xticklabels(custom_labels, rotation=60, ha="right", fontsize=8)
ax.set_xlabel("Test Execution Date + Group Details", fontsize=12)
ax.set_ylabel("Cumulative Test Count", fontsize=12)

# Place legend outside the plot to avoid clutter
ax.legend(bbox_to_anchor=(1.05, 1), loc="upper left", fontsize=10)
ax.grid(alpha=0.3)
plt.tight_layout()
plt.show()

Key Takeaways for Multi-Label X-axes in Grouped Pandas Plots

  • Subplot Titles are King: For most cases, using subplots with group-specific titles is the cleanest way to link your plot to its group—no clutter on the X-axis.
  • Extended X-axis Labels: If you need group context directly near the date axis, add the group info as a second line in the X-axis label (as shown in Step 2).
  • Multi-Line Tick Labels: Use this only if you must show group info on the ticks themselves—adjust rotation and font size to avoid overlapping text.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:20:54