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

Python中消除科学计数法时遭遇AttributeError的解决方法

解决柱状图Y轴显示实际数值而非科学计数法的问题

修复方法

  • 从matplotlib.ticker模块导入ScalarFormatter(之前报错“名称未定义”是因为未导入该类)
  • 获取绘图的坐标轴对象,手动指定Y轴使用ScalarFormatter,并禁用科学计数法与偏移量

修改后的完整代码

import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter
import pandas as pd

fig = plt.figure(figsize = (10, 5))
# 保存绘图返回的Axes对象,用于后续设置坐标轴格式
ax = pd.Series(y_vals, index=x_vals).nlargest(10).plot.bar(color ='maroon', width = 0.4)
plt.xlabel("Company")
plt.xticks(rotation = 360)
plt.ylabel("Value of Purchases")
plt.title("Top Insider Purchases of the Year")

# 配置Y轴格式化规则
y_formatter = ScalarFormatter(useOffset=False)
y_formatter.set_scientific(False)
ax.yaxis.set_major_formatter(y_formatter)

plt.show()

说明

直接使用plt.ticklabel_format(useOffset=False)报错,是因为pandas绘制柱状图时,Y轴默认使用的不是ScalarFormatter,必须手动指定格式化器后再调整显示规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:20:28