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

如何让Matplotlib绘图的X轴从1开始而非0?

让Matplotlib绘图X轴起始值为1的方法

要解决X轴从0开始的问题,最直接的方式是使用Matplotlib的plt.xlim()函数强制设置X轴的左边界为1。Matplotlib默认会自动调整轴范围以包含所有数据并留出少量空白,这就是你的X轴显示到0的原因。

修改后的代码如下:

import math
import matplotlib.pyplot as plt
import gmpy2

def pi_count(n):
    result = []
    count = 0
    for h in range(1, n+1):
        if gmpy2.is_prime(h):
            count += 1
        result.append(count)
    return result

lim = 10**3
liste = pi_count(lim)

plt.plot(list(range(1, lim+1)), liste)
# 强制X轴左边界从1开始
plt.xlim(left=1)
plt.show()

如果你需要更精细地控制刻度显示,也可以使用plt.xticks()指定刻度的起始值和步长,例如:

plt.xticks(range(1, lim+1, 100))

这会让X轴刻度从1开始,每隔100显示一个刻度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:52:02