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

时间序列折线图显示异常,如何实现线条正常连续连接?

时间序列折线图无法连续连接的解决方法

问题说明

绘制的时间序列折线图线条异常,无法正常连续连接,使用的代码如下:

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:06:01