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

Python中基于Method列与多需求列的直方图构建问题

Hey there! Let's troubleshoot that messy bar chart you're dealing with—those unreadable plots and weird thick X-axis lines are super frustrating, but we can fix this. Here are actionable steps to get your visualization looking clean and informative:

1. First, Clean Up Your Data

The thick X-axis lines are likely caused by duplicate method entries stacking on top of each other (looking at your sample data, methods 1, 3, 5, 6 repeat). Let's consolidate these first:

import pandas as pd

# Load your data (replace with your actual load method)
# df = pd.read_csv("your_data_file.csv")

# Group by method and sum the requirement values
df_consolidated = df.groupby('method').sum().reset_index()

This ensures each method only appears once in your dataset, eliminating overlapping bars that cause those messy X-axis artifacts.

2. Optimize the Pandas Bar Plot

Now use the cleaned data with adjusted plot parameters to avoid crowding and improve readability:

import matplotlib.pyplot as plt

# Generate the bar chart with optimized settings
ax = df_consolidated.plot.bar(
    x='method',
    y=['RequirementT', 'RequirementN', 'RequirementU'],
    figsize=(10, 6),  # Wider canvas to prevent overlap
    rot=0,  # Keep X-axis labels horizontal for readability
    width=0.8,  # Set a reasonable bar width
    edgecolor='white',  # Add white borders between bars for clarity
    colormap='viridis'  # Optional: Use a distinct color palette
)

# Add clear labels and title
ax.set_title('Requirement Counts by Method', fontsize=14)
ax.set_xlabel('Method ID', fontsize=12)
ax.set_ylabel('Number of Requirements', fontsize=12)

# Adjust legend position to avoid covering bars
ax.legend(loc='upper right', bbox_to_anchor=(1.2, 1))

# Auto-adjust layout to prevent label cutoff
plt.tight_layout()
plt.show()

3. If Pandas Plot Still Acts Up, Use Matplotlib Directly

Sometimes pandas' plot wrapper can have odd styling quirks. For full control, build the chart directly with Matplotlib:

import numpy as np

# Prepare data from the consolidated dataframe
methods = df_consolidated['method'].values
x = np.arange(len(methods))  # X-axis positions
bar_width = 0.25  # Width for each requirement type's bar

fig, ax = plt.subplots(figsize=(10, 6))

# Plot each requirement type as a separate set of bars
bar_t = ax.bar(x - bar_width, df_consolidated['RequirementT'], bar_width, label='RequirementT')
bar_n = ax.bar(x, df_consolidated['RequirementN'], bar_width, label='RequirementN')
bar_u = ax.bar(x + bar_width, df_consolidated['RequirementU'], bar_width, label='RequirementU')

# Customize the plot
ax.set_xlabel('Method ID', fontsize=12)
ax.set_ylabel('Number of Requirements', fontsize=12)
ax.set_title('Requirement Counts by Method', fontsize=14)
ax.set_xticks(x)
ax.set_xticklabels(methods)
ax.legend()

# Optional: Add value labels on top of bars for clarity
def add_bar_labels(bars):
    for bar in bars:
        height = bar.get_height()
        ax.annotate(f'{height}',
                    xy=(bar.get_x() + bar.get_width()/2, height),
                    xytext=(0, 3),  # Small vertical offset
                    textcoords='offset points',
                    ha='center', va='bottom')

add_bar_labels(bar_t)
add_bar_labels(bar_n)
add_bar_labels(bar_u)

fig.tight_layout()
plt.show()

Why This Works

  • Consolidating duplicate method entries removes overlapping bars that caused the thick X-axis lines.
  • Adjusting figsize, rot, and width ensures the plot isn't cramped and labels are readable.
  • Using Matplotlib directly gives you full control over every element of the chart, avoiding any unexpected behavior from pandas' plot wrapper.

内容的提问来源于stack exchange,提问作者منى

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 21:32:26