Python堆叠条形图无法匹配Excel样式,A数组数值未显示求助
Ah, I see the issue here! The problem comes down to two key things: matplotlib's default Y-axis range cuts off your negative values in array A, and the stacking logic wasn't paired with a view that shows all your data. Let's get this fixed to match your Excel chart.
Why Your Current Code Isn't Showing A
When you plot the negative values in A, matplotlib draws them downward from the 0 line—but by default, the Y-axis only shows positive values. That means your A bars are hidden below the axis! On top of that, stacking B on A with bottom=A makes the B bars start at the negative A values and extend upward, but you can't see the A portion because it's outside the default view.
Corrected Code
Here's the adjusted version that will display both A and B properly, just like Excel:
import matplotlib.pyplot as plt def graph2Peak(self): # Keeping self since your original code uses it (assuming it's part of a class) A = [-1478, -16411, 5986, 0] B = [14933, 29866, 7466, 14933] X = range(4) # Calculate full range of values to set Y-axis bounds combined_values = [a + b for a, b in zip(A, B)] y_min = min(A + combined_values) - 1000 # Add small buffer to avoid cutting off bars y_max = max(A + combined_values) + 1000 # Plot both bar sets with correct stacking plt.bar(X, A, color='b', label='A') plt.bar(X, B, color='r', bottom=A, label='B') # Adjust Y-axis to show all data plt.ylim(y_min, y_max) # Add Excel-like labels and legend (optional but improves readability) plt.xticks(X, ['Category 1', 'Category 2', 'Category 3', 'Category 4']) plt.ylabel('Value') plt.title('Stacked Bar Chart (Matching Excel)') plt.legend() plt.show()
Key Changes Explained
- Y-axis Range Fix: We calculate the minimum value from both
Aand the total stacked values (A+B) to make sure the negativeAbars are visible. Adding a small buffer ensures no part of the bars gets cut off at the edges. - Clear Labeling: Just like Excel, adding custom X-axis labels, a title, and a legend makes the chart easier to interpret.
- Proper Stacking: The
bottom=Aparameter is correct for stacking—we just needed to make sure the Y-axis shows the full range of your data so nothing is hidden.
内容的提问来源于stack exchange,提问作者DJS

