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

如何修改Matplotlib代码将图表Y轴起始点设为0?

问题需求
  • 数据集包含Time列与Jolt 1、Jolt 2等数值列,需将Time设为X轴索引,各Jolt列作为Y轴指标绘制折线图
  • 要求Y轴起始点固定为0,不受数据集中数值范围影响
  • 当前图表中蓝色曲线从Y=0开始,但橙色曲线起始点高于0,需调整为两条曲线均从Y=0起始,便于直观对比趋势
现有代码
import pandas as pd
import matplotlib.pyplot as plt

df.set_index('Time').plot()
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
修改方案

可以通过两种方式实现需求:

方法1:使用matplotlib强制设置Y轴范围

在绘图后添加Y轴下限设置,直接固定Y轴从0开始:

import pandas as pd
import matplotlib.pyplot as plt

ax = df.set_index('Time').plot()
ax.set_ylim(bottom=0)  # 强制Y轴起始点为0
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
plt.show()

方法2:在pandas绘图时直接指定Y轴范围

调用plot方法时通过ylim参数直接定义Y轴范围:

import pandas as pd
import matplotlib.pyplot as plt

df.set_index('Time').plot(ylim=(0, None))  # None表示自动适配数据的上限值
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
plt.show()

说明

两种方法都能确保Y轴从0起始,让所有曲线在同一基准线开始对比,完全满足趋势直观对比的需求。如果需要手动指定Y轴上限,只需将None替换为具体数值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:24:19