Skip to main content
 首页 » 编程设计

python之如何避免 matplotlib 散点图中轴上的负数

2025年05月04日99JustinYoung

我正在使用 Python 散点图绘制一个简单的散点图。但无论我如何设置轴,也无论我没有任何负值,我都会在 x 轴上得到负值。如何强制轴从 0 开始?

我的代码:

fig, ax = plt.subplots(1) 
ax.scatter(lengths,breadths, alpha=0.3, color="#e74c3c", edgecolors='none') 
spines_to_remove = ['top', 'right'] 
for spine in spines_to_remove: 
    ax.spines[spine].set_visible(False) 
ax.xaxis.set_ticks_position('none') 
ax.yaxis.set_ticks_position('none') 
ax.xaxis.set_view_interval(0,400) 
ax.yaxis.set_view_interval(0,90) 
figname = 'scatterlengthsbreadths.pdf' 
fig.savefig(figname, bbox_inches='tight')   

请您参考如下方法:

您可以使用 ax.set_xlim(lower_limit, upper_limit)选择您的 x 限制。请注意,对于 y 限制,有一个类似的命令 ax.set_ylim。

请注意,如果您只是使用 pyplot 接口(interface),即不使用 fig 和 ax,则命令为 plt.xlim().

例如:

import matplotlib.pyplot as plt 
 
x = [1,2,3] 
y = [4,5,6] 
 
fig, ax = plt.subplots() 
 
ax.plot(x, y) 
 
ax.set_xlim(0, 10) 
 
plt.show()