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

如何在Pandas中绘制剔除指定范围异常值的箱线图并旋转标题?

Solution for Your Boxplot Requirements

Let's break down your needs into actionable, easy-to-adapt code steps, with explanations tailored to your scenario:

1. Preparations & Setup

First, import the required libraries and define your target value range:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns  # For cleaner, more polished boxplots (matplotlib alone works too)

# Define your outlier exclusion range
lower_bound = 68
upper_bound = 72

2. Decide Whether to Plot (Avoid Unreadable Headers)

We’ll first count how many values fall outside your 68-72 range per column. If only a tiny number of outliers exist, we skip plotting entirely to prevent cramped, unreadable column headers:

# Calculate outlier count for each column
outlier_counts = ((df < lower_bound) | (df > upper_bound)).sum()

# Set your threshold for "too few outliers" (adjust this based on your dataset size)
# Example: Only plot if a column has 3+ outliers outside the range
outlier_threshold = 3
columns_to_plot = outlier_counts[outlier_counts >= outlier_threshold].index.tolist()

3. Generate Boxplot (Filtered Data + Rotated Labels)

If there are enough outliers to justify plotting, we’ll filter the data to exclude values outside 68-72, then create the boxplot with rotated labels for readability:

if columns_to_plot:
    # Filter data to keep only values within 68-72 for target columns
    filtered_data = df[columns_to_plot].apply(
        lambda col: col[(col >= lower_bound) & (col <= upper_limit)]
    )
    
    # Create the boxplot
    plt.figure(figsize=(10, 6))
    ax = sns.boxplot(data=filtered_data)  # Use plt.boxplot() if you prefer raw matplotlib
    
    # Rotate x-axis labels (column headers) 90 degrees to fix readability issues
    ax.set_xticklabels(ax.get_xticklabels(), rotation=90)
    
    # Optional: Add a clear title (if you meant rotating the main title, add rotation=90 here)
    plt.title("Boxplot (Filtered to 68-72 Range)", fontsize=12)
    
    # Adjust layout to prevent label cutoff
    plt.tight_layout()
    plt.show()
else:
    print("Insufficient outliers outside 68-72 range; skipping boxplot to avoid unreadable headers.")

Key Customization Tips

  • Use percentage-based threshold: Instead of a fixed count, you can filter columns where outliers make up >5% of the data:
    outlier_ratios = ((df < lower_bound) | (df > upper_bound)).mean()
    columns_to_plot = outlier_ratios[outlier_ratios > 0.05].index.tolist()
    
  • Matplotlib-only alternative: If you don’t want to use Seaborn, replace the sns.boxplot block with:
    ax = plt.boxplot(filtered_data.dropna().values)
    plt.xticks(range(1, len(columns_to_plot)+1), columns_to_plot, rotation=90)
    
  • Rotate main title: If you specifically need the plot’s main title rotated 90 degrees (not column labels), modify the title line to:
    plt.title("Your Custom Boxplot Title", rotation=90)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:13:01