Python时间序列图表Y值绘制异常,如何修正为正确时序图?
问题解决:修正时间序列折线图
问题原因
你的production列是带逗号的字符串类型,matplotlib在绘制时会把字符串当作离散类别,按字典序排序后绘制,所以出现了不符合预期的正斜率直线,而非实际的数值变化趋势。
解决方案
需要先将字符串格式的数值转换为可计算的数值类型,再绘制图表:
1. 数据清洗要点
- 移除
production中的逗号,转换为整数类型 - 若后续需要绘制
imports,可同步移除其中的$和逗号,转换为整数类型
2. 修改后的完整代码
import pandas as pd import matplotlib.pyplot as plt # 初始化数据框 df = pd.DataFrame([(2003, '2,061,995', '$55,812,008,171'), (2004, '1,991,394', '$78,277,321,635'), (2005, '1,892,095', '$107,478,346,132'), (2006, '1,856,340', '$131,528,352,871'), (2007, '1,851,974', '$147,375,398,002')], columns=['Year', 'production', 'imports']) # 数据清洗:将字符串格式的数值转为整数 df['production'] = df['production'].str.replace(',', '').astype(int) # 可选:同步处理imports列 df['imports'] = df['imports'].str.replace('$', '').str.replace(',', '').astype(int) def plot_df(df, x, y, title="", xlabel='Year', ylabel='US Domestic Crude Oil Production', dpi=100): plt.figure(figsize=(15,4), dpi=dpi) plt.plot(x, y, color='tab:red') plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel) plt.show() # 调用绘图函数 plot_df(df, x=df['Year'], y=df['production'], title='US Domestic Crude Oil Production')
效果说明
处理后production列变为整数类型,matplotlib会基于实际数值绘制折线,能正确展示2003-2007年原油产量逐年下降的趋势。
内容的提问来源于stack exchange,提问作者scmings
相关产品推荐
相关产品推荐

