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
相关产品推荐
相关产品推荐

