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

基于Pandas与Matplotlib创建子公司维度堆叠柱状图的问题求助(含错误排查、优化及批量实现需求)

Stacked Bar Chart Solutions for Your Multi-Subsidiary Dataset

Hey there! Let's work through your stacked bar chart problems one by one. I'll break down each question with actionable fixes and optimized approaches.

1. Fixing the Stacked Bar Chart Error

The error you're seeing happens because the bottom parameter in plt.bar() expects a numeric array/series, not an entire DataFrame. When you pass EURETAIL instead of EURETAIL['value'], matplotlib doesn't know how to process the full dataset. Here's the corrected code:

import pandas as pd
import matplotlib.pyplot as plt

# Your original data
df = pd.DataFrame({
    'subsidiary': ['EU','EU','EU','EU','EU','EU','EU','EU','EU','US','US','US','US','US','US','US','US','US'],
    'date': ['2019-03','2019-04', '2019-05','2019-03','2019-04', '2019-05','2019-03','2019-04', '2019-05','2019-03','2019-04', '2019-05','2019-03','2019-04', '2019-05','2019-03','2019-04', '2019-05'],
    'business': ['RETAIL','RETAIL','RETAIL','CORP','CORP','CORP','PUBLIC','PUBLIC','PUBLIC','RETAIL','RETAIL','RETAIL','CORP','CORP','CORP','PUBLIC','PUBLIC','PUBLIC'],
    'value': [500.36,600.45,700.55,750.66,950.89,1300.13,100.05,120.00,150.01,800.79,900.55,1000,3500.79,5000.36,4500.25,50.17,75.25,90.33]
})

# Get sorted unique dates (to ensure x-axis order is correct)
x = sorted(df['date'].unique())

# Filter subsets correctly, and ensure they match the x-axis order
EURETAIL = df[(df['subsidiary']=='EU') & (df['business']=='RETAIL')].set_index('date').reindex(x)['value']
EUCORP = df[(df['subsidiary']=='EU') & (df['business']=='CORP')].set_index('date').reindex(x)['value']
EUPUBLIC = df[(df['subsidiary']=='EU') & (df['business']=='PUBLIC')].set_index('date').reindex(x)['value']

# Now plot with numeric values for bottom
plt.figure(figsize=(8,5))
plotEURETAIL = plt.bar(x=x, height=EURETAIL, width=.35, label='RETAIL')
plotEUCORP = plt.bar(x=x, height=EUCORP, width=.35, bottom=EURETAIL, label='CORP')
plotEUPUBLIC = plt.bar(x=x, height=EUPUBLIC, width=.35, bottom=EURETAIL + EUCORP, label='PUBLIC')

plt.title('EU Subsidiary Business Values (Stacked)')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.show()

Key fixes:

  • We sort the dates to keep the x-axis in chronological order
  • We reindex each subset to match the sorted x-axis (ensures alignment of values)
  • We pass only the 'value' series to bottom instead of the full DataFrame

2. A More Optimal Approach (No Manual Subset Creation)

Your current method works, but creating separate DataFrames for each business type is repetitive. Instead, use pandas' pivot() function to reshape your data into a wide format, then plot directly with pandas' built-in stacked bar chart:

# Reshape EU data into wide format
eu_wide = df[df['subsidiary']=='EU'].pivot(index='date', columns='business', values='value').sort_index()

# Plot stacked bar chart in one line
eu_wide.plot(kind='bar', stacked=True, figsize=(8,5), width=0.35)
plt.title('EU Subsidiary Business Values (Stacked)')
plt.xlabel('Date')
plt.ylabel('Value')
plt.show()

This approach is cleaner, less error-prone, and automatically handles alignment of dates and business types.

3. Batch-Generate Stacked Charts for All Subsidiaries

To avoid creating charts one by one, loop through each unique subsidiary, reshape the data, and plot. Here's how:

# Get all unique subsidiaries
subsidiaries = df['subsidiary'].unique()

# Loop through each subsidiary
for sub in subsidiaries:
    # Reshape data for the current subsidiary
    sub_wide = df[df['subsidiary']==sub].pivot(index='date', columns='business', values='value').sort_index()
    
    # Create a new figure for each subsidiary
    plt.figure(figsize=(8,5))
    sub_wide.plot(kind='bar', stacked=True, width=0.35, ax=plt.gca())
    
    # Add titles and labels
    plt.title(f'{sub} Subsidiary Business Values (Stacked)')
    plt.xlabel('Date')
    plt.ylabel('Value')
    plt.tight_layout()  # Ensures labels don't get cut off
    plt.show()

This code will automatically generate a stacked bar chart for every subsidiary in your dataset—no manual subsetting required!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 12:19:09