时间序列折线图显示异常,如何实现线条正常连续连接?
时间序列折线图无法连续连接的解决方法
问题说明
绘制的时间序列折线图线条异常,无法正常连续连接,使用的代码如下:
plt.figure(figsize=(25,5)) plt.plot(dt['Period'], dt['Sales_quantity'], marker = 'x', linestyle = '-') plt.title('Sales Quantity over a period of time') plt.xlabel('Period') plt.ylabel('Sales Quantity') plt.show()
异常图表:
示例数据框:
解决步骤
- 转换时间列类型:从数据框截图可见,
Period列是字符串格式的年月(如2022-01),matplotlib无法识别其时间顺序,会按字符串排序规则处理,导致折线错乱。先将该列转换为datetime类型:dt['Period'] = pd.to_datetime(dt['Period']) - 按时间排序数据:确保数据按时间从小到大排列,避免因数据顺序混乱造成折线跳变:
dt = dt.sort_values('Period') - 重新绘图:完成上述处理后,运行原绘图代码,折线即可按时间顺序正常连续连接。
内容的提问来源于stack exchange,提问作者Wutthikorn Niyomthong
相关产品推荐
相关产品推荐

