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

Python:Matplotlib柱状图Y轴起始值设为0的问题求助

Fix: Matplotlib Bar Chart Doesn't Display Full Bars Starting at Y=0

Hey Connor, let's troubleshoot why your bar chart isn't showing the full green bars starting from Y=0 even though you added plt.ylim(ymin=0). Here's what you can do to fix this:

Common Causes & Solutions

The issue likely stems from either an ambiguous Y-axis limit setting, or matplotlib's automatic scaling overriding your explicit ymin value. Here are two reliable fixes:

1. Use bottom=0 for Explicit Y-Axis Start

Replace your existing plt.ylim(ymin=0) with a more explicit parameter to ensure matplotlib respects your starting point:

plt.ylim(bottom=0)

This directly tells matplotlib to set the bottom of the Y-axis to 0, leaving no room for automatic scaling to override it.

2. Add a Top Buffer to Avoid Truncation

If your tallest bar is getting cut off at the top of the chart, you can also set a clear upper limit with a small buffer to improve readability:

# Calculate the maximum value in your Y dataset and add a 10% buffer
max_votes = max(Y)
plt.ylim(bottom=0, top=max_votes * 1.1)

This ensures the Y-axis starts at 0 and has enough space at the top to fully display your tallest bar.

Modified Full Code

Here's your updated code with these fixes, plus more descriptive axis labels for clarity:

import pandas as pd
import matplotlib.pyplot as plt

pd.options.display.max_rows = 100
pd.set_option('display.max_columns', None)

western_counties = pd.read_csv('2018_governor_results_western_ny_dem.csv')
df = pd.DataFrame(western_counties)

X = list(df.iloc[:, 0])
Y = list(df.iloc[:, 1])

plt.bar(X, Y, color='g')
plt.title('Region 1 - Western New York')
plt.xlabel('County')  # Updated to reflect your X-axis data (counties)
plt.ylabel('Democratic Votes')  # Updated to match your dataset's metric

# Force Y-axis to start at 0 with a top buffer
max_votes = max(Y)
plt.ylim(bottom=0, top=max_votes * 1.1)

plt.show()

Quick Check

If this still doesn't work, double-check that there's no other code after plt.ylim that modifies the Y-axis (like plt.axis('tight') or another plt.ylim call) — these could override your settings.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 06:48:30