如何为堆叠柱状图添加标注:含列总计与区块百分比
Adding Total Values to Stacked Bar Chart with Percentage Labels
Got it, you're halfway there with your stacked bar chart—nice work on the percentage labels! To add the total revenue value at the top of each column, we just need to calculate the quarterly totals and place those labels at the peak of each bar stack. Here's how to modify your code:
Modified Code
import matplotlib.pyplot as plt # Assuming df_data_2 is your DataFrame with rows as categories, columns as quarters df_data_2 = df_data_2.round(2) # Calculate percentages for each segment counter = df_data_2.unstack().unstack() percentage_dist = 100 * counter.divide(counter.sum(axis=1), axis=0) # Create the stacked bar chart ax = percentage_dist.plot.bar(stacked=True) # Add percentage labels to each segment for p in ax.patches: width, height = p.get_width(), p.get_height() x, y = p.get_xy() # Skip labeling tiny/zero segments to avoid clutter if height > 0.1: ax.text(x + width/2, y + height/2, '{:.1f} %'.format(height), horizontalalignment='center', verticalalignment='center', fontsize=8) # Calculate total revenue per quarter (using original data values) quarter_totals = df_data_2.sum(axis=0) # Add total labels at the top of each bar stack for i, total in enumerate(quarter_totals): # Get the top position of the current quarter's bar stack stack_segments = ax.patches[i * len(df_data_2) : (i+1)*len(df_data_2)] stack_top = stack_segments[-1].get_y() + stack_segments[-1].get_height() # Place label slightly above the stack for readability ax.text(i, stack_top + 0.8, 'Total: ${:.1f}M'.format(total), horizontalalignment='center', fontweight='bold', fontsize=9) # Final chart formatting plt.xlabel("QTR") plt.ylabel("Revenue") plt.title("On Prem Tran Rev: Quarterly Performance $M (% of Total)") # Move legend outside the plot to avoid overlapping plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.tight_layout() # Ensure all elements fit without cutting off plt.show()
Key Changes Explained:
- Quarterly Totals Calculation: We use
df_data_2.sum(axis=0)to pull the actual total revenue for each quarter from your original dataset (not the percentage values). - Total Label Placement: For each quarter, we target the last segment in its bar stack to find the top position, then add a bold label slightly above it so it doesn't overlap with the stack.
- Clutter Reduction: Added a check to skip labeling segments with less than 0.1% height—this keeps the chart clean without hiding meaningful data.
- Layout Tweaks: Moved the legend outside the plot area and used
tight_layout()to make sure all labels, titles, and the legend are fully visible.
内容的提问来源于stack exchange,提问作者James Parke
相关产品推荐
相关产品推荐

