Matplotlib绘图时价格数值从千位被缩小为个位的异常问题
问题解决思路
先排查核心问题点
你遇到的情况大概率是Matplotlib自动启用了科学计数法+轴偏移量,导致原本的万级Price数值被缩放显示;或者是绘图时轴参数传反、DataFrame字段类型异常。按以下步骤逐一排查:
1. 确认DataFrame数据的正确性
先打印Price字段的类型和统计信息,排除数据本身被篡改的可能:
# 查看字段类型 print(car_df[['Price', 'Year', 'Mileage']].dtypes) # 查看Price的数值范围 print(car_df['Price'].describe())
如果输出里Price的max/min还是符合数千到数百万的预期,且dtype是int64或float64,说明数据没问题,问题出在绘图环节。
2. 修正绘图的轴显示格式
直接强制关闭轴的自动偏移和科学计数法,让Price数值以原始形式展示:
from matplotlib.ticker import ScalarFormatter fig, ax = plt.subplots() # 确认你的x/y轴参数正确,比如要画Price vs Year: ax.scatter(car_df['Price'], car_df['Year']) ax.set_xlabel('Price') ax.set_ylabel('Year') # 强制显示原始数值,关闭自动偏移 ax.xaxis.set_major_formatter(ScalarFormatter(useOffset=False)) # 自动调整布局,避免标签被截断 plt.tight_layout() plt.show()
这样就能让x轴显示原始的Price数值(比如20000),而不是缩放后的小数。
3. 检查Car类与DataFrame创建逻辑
既然添加Mileage前没问题,要确认新增Mileage后,Car类的初始化逻辑有没有影响Price的赋值:
class Car: def __init__(self, year, price, mileage): self.Year = year # 确保这里没有对Price做额外缩放,比如price / 1000000 self.Price = price self.Mileage = mileage
另外,检查从实例生成DataFrame的代码,确保没有字段错位:
# 标准转换方式,避免字段遗漏或错位 car_df = pd.DataFrame([car.__dict__ for car in car_data]) # 查看前5行数据,确认Price列数值正确 print(car_df.head())
4. 排除Mileage的干扰
如果Mileage的数值量级远大于Price(比如百万级),Matplotlib可能会为了适配整体数据范围而强制缩放轴。你可以先临时去掉Mileage列再绘图,验证是否恢复正常:
# 临时删除Mileage列后绘图 temp_df = car_df.drop('Mileage', axis=1) fig, ax = plt.subplots() ax.scatter(temp_df['Price'], temp_df['Year']) plt.show()
如果恢复正常,说明是多字段共存时Matplotlib的自动缩放逻辑导致的,用步骤2的强制格式化就能解决。
内容的提问来源于stack exchange,提问作者Gleb
相关产品推荐
相关产品推荐

