如何用Matplotlib实现Excel式的100%堆叠条形图绘制?
100% Stacked Horizontal Bar Chart with Matplotlib & Pandas
Absolutely! You can totally replicate a 100% stacked bar chart (the horizontal style, just like your Excel example) using Matplotlib and Pandas. The key fix you need is normalizing your data so each row sums to 1 (100%)—your current code makes a stacked bar chart, but not the 100% scaled version you're aiming for.
Step-by-Step Breakdown
- Normalize the Dataset: Divide every value in a row by the total sum of that row. This ensures each row adds up to 1, which translates directly to 100% in the chart.
- Generate the 100% Stacked Chart: Use the normalized dataframe to create the horizontal stacked bar plot.
- Polish the Visual: Tweak labels, legends, and add optional percentage annotations to make the chart easy to read.
Modified Working Code
import pandas as pd import matplotlib.pyplot as plt # Your original dataset data = [ [0.4, 0.3, 0.2, 0.1], [0.5, 0.3, 0.6, 0.1], [0.1, 0.4, 0.2, 0.8], ] columns = ["A", "B", "C", "D"] df = pd.DataFrame(data=data, columns=columns, index=["Empty", "Wrong", "Correct"]) # Normalize data so each row sums to 1 (100%) df_normalized = df.div(df.sum(axis=1), axis=0) # Create the 100% stacked horizontal bar chart ax = df_normalized.plot(kind="barh", stacked=True, figsize=(10, 6)) # Add percentage labels to each bar segment for p in ax.patches: width = p.get_width() if width > 0: # Skip segments with no value ax.text( p.get_x() + width / 2, p.get_y() + p.get_height() / 2, f"{width:.1%}", ha="center", va="center", fontsize=10 ) # Customize chart elements plt.ylabel("Category") plt.xlabel("Percentage") plt.title("100% Stacked Horizontal Bar Chart") plt.legend(title="Groups", bbox_to_anchor=(1.05, 1), loc="upper left") plt.tight_layout() plt.show() # Print normalized data for reference print("Normalized Data (each row sums to 1):") print(df_normalized)
Quick Explanations
- The line
df.div(df.sum(axis=1), axis=0)handles normalization:axis=1calculates the sum of each row, andaxis=0ensures we divide each value by its row's total. - Adding percentage annotations makes it instantly clear what proportion each segment takes up.
- Moving the legend to the side prevents overlap with the chart, which boosts readability.
内容的提问来源于stack exchange,提问作者Salvo Dragotta
相关产品推荐
相关产品推荐

