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

如何为Matplotlib箱线图的每个类别添加记录数量?

Add Record Counts to Each Box in Your Pandas Boxplot

Great question! Adding sample size labels makes your boxplot way more informative—here's a straightforward way to extend your existing code to include them:

Step 1: Calculate record counts per stage

First, we’ll get the number of observations for each stage, making sure the order matches how stages appear in your boxplot:

# Get the count of records for each stage (order matches boxplot categories)
stage_counts = df.groupby('stage').size().values

Step 2: Draw the boxplot and capture the axis object

Modify your original code to store the plot’s axis (ax)—this lets us add text annotations later:

# Create your boxplot and save the axis reference
ax = df.assign(index=df.groupby('stage').cumcount())\
       .pivot('index', 'stage', 'days')\
       .plot(kind='box', sym='bD', showmeans=True)

Step 3: Add count labels to each box

Loop through each stage’s count and place a label above its corresponding box. We’ll position labels near the top of the plot (adjust the y-position if you want them closer to the boxes):

# Add "n=X" labels above each box
for idx, count in enumerate(stage_counts):
    ax.text(
        x=idx,
        y=ax.get_ylim()[1] * 0.95,  # 95% of the y-axis maximum value
        s=f'n={count}',
        ha='center',  # Center the label horizontally over the box
        fontsize=10
    )

Full Combined Code

Here’s everything put together, with optional plot tweaks:

import pandas as pd
import matplotlib.pyplot as plt

# Your existing data (replace with your actual DataFrame)
# df = pd.read_csv("your_data.csv")

# Calculate stage record counts
stage_counts = df.groupby('stage').size().values

# Generate boxplot with axis reference
ax = df.assign(index=df.groupby('stage').cumcount())\
       .pivot('index', 'stage', 'days')\
       .plot(kind='box', sym='bD', showmeans=True)

# Add sample count labels
for idx, count in enumerate(stage_counts):
    ax.text(idx, ax.get_ylim()[1] * 0.95, f'n={count}', ha='center', fontsize=10)

# Optional: Customize plot labels
ax.set_title('Days by Stage (with Sample Counts)')
ax.set_ylabel('Number of Days')

plt.show()

Quick Notes

  • If you prefer labels right above each box instead of the plot’s top, you can extract the boxplot’s statistical data to target each box’s upper quartile position. The fixed y-position above works for most use cases though.
  • The ha='center' parameter ensures each label is perfectly aligned over its box.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:52:34