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

如何用最简最优最快方式基于pandas的payout_df复刻Excel堆叠柱状图?

Quick & Simple Stacked Bar Chart for Your Payout Data

Hey there! I’ve been in your shoes—trying to replicate an Excel stacked bar chart in Python can feel frustrating when you’re fumbling with different methods, but pandas’ built-in plotting is the fastest, most straightforward way to get this done. Let’s break it down step by step.

First, Let’s Assume Your Data Structure

Chances are your payout_df looks something like this (with a category column and multiple payout value columns):

CategoryPayout_1Payout_2Payout_3
Jan450022001800
Feb520028002100
............

If your data is in "long format" (one row per category-payout pair), we’ll fix that first—otherwise, skip right to plotting.

1. (If Needed) Reshape Long Data to Wide Format

If your data looks like this instead:

CategoryPayout_TypeAmount
JanPayout_14500
JanPayout_22200
.........

Use pivot() to convert it to wide format (the structure Excel uses for stacked charts):

wide_payout_df = payout_df.pivot(index='Category', columns='Payout_Type', values='Amount')

2. Plot the Stacked Bar Chart in 2 Lines (Plus Tweaks)

Pandas wraps matplotlib’s functionality, so you can create the stacked bar chart with a single plot call:

import pandas as pd
import matplotlib.pyplot as plt

# Create the stacked bar chart
ax = payout_df.plot(kind='bar', stacked=True, figsize=(10, 6))  # Use wide_payout_df if you reshaped

# Add labels and title to match Excel's clarity
plt.title('Monthly Payout Breakdown', fontsize=14)
plt.xlabel('Month', fontsize=12)
plt.ylabel('Total Payout ($)', fontsize=12)

# Optional: Add value labels inside each segment (super helpful for readability)
for container in ax.containers:
    ax.bar_label(container, label_type='center', fontsize=10)

# Adjust legend position so it doesn't overlap the chart
plt.legend(loc='upper right', bbox_to_anchor=(1.25, 1))

plt.show()

Why This Works Best

  • No extra libraries: You’re already using pandas, so no need to install seaborn or other tools unless you want fancy styling.
  • One-line core logic: The stacked=True parameter does all the heavy lifting that would require looping through series if you used raw matplotlib.
  • Easy to tweak: Adjust colors, sizes, labels, and legends with simple matplotlib calls—just like you’d tweak in Excel.

If your data has a different structure (like dates as the index), just adjust the x parameter in plot() or set your category column as the index first. This method should adapt to most common payout data formats.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:30:26