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

如何在Pandas Series绘图声明中添加X、Y轴标签?

解决Series绘图时设置轴标签的问题

嘿,作为Python新手碰到这个小问题太正常啦!我来给你几个简单的解决办法,都能直接在绘图相关代码里设置轴标签,完全不用纠结是不是DataFrame~

方法1:直接在plot()方法里传入轴标签参数

如果你的pandas版本比较新(大概0.25及以上),可以直接在plot()方法里添加xlabel和ylabel参数,一步到位:

# plot graph for counts per minute
plt.axes(frameon=0) # reduce chart junk
minute_ct.plot(
    kind='line', 
    rot=0, 
    title="Summary of packet activity", 
    figsize=(20,10),
    xlabel="时间(分钟)",  # 直接设置X轴标签
    ylabel="数据包数量"     # 直接设置Y轴标签
).grid(False)
plt.show()

方法2:获取Axes对象后设置标签

如果你的pandas版本偏旧,不支持直接传xlabel/ylabel,可以先把plot()返回的Axes对象存下来,再调用专属方法设置标签:

# plot graph for counts per minute
plt.axes(frameon=0) # reduce chart junk
ax = minute_ct.plot(
    kind='line', 
    rot=0, 
    title="Summary of packet activity", 
    figsize=(20,10)
)
ax.grid(False)
ax.set_xlabel("时间(分钟)")  # 通过Axes对象设置X轴标签
ax.set_ylabel("数据包数量")  # 通过Axes对象设置Y轴标签
plt.show()

方法3:用matplotlib全局函数设置

你也可以直接调用matplotlib的全局函数plt.xlabel()和plt.ylabel(),放在绘图代码之后、plt.show()之前就行:

# plot graph for counts per minute
plt.axes(frameon=0) # reduce chart junk
minute_ct.plot(kind='line', rot=0, title="Summary of packet activity", figsize=(20,10)).grid(False)
plt.xlabel("时间(分钟)")
plt.ylabel("数据包数量")
plt.show()

本质上来说,不管你用的是Series还是DataFrame的plot方法,最终都是基于matplotlib的Axes对象在绘图,所以这几种方式都能轻松搞定轴标签的设置~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:37:46