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

Matplotlib折线图数据排序异常,求修正方法

izip

运行结果显示数据顺序为1、2、4、3,预期应为1、2、3、4。

以下是我的绘图代码:

import csv
import matplotlib.pyplot as plt

time = []
total = []
  
with open('new.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter = ',')
      
    for row in plots:
        time.append(row[0])
        total.append(row[1])
  
plt.plot(time, total)
plt.xlabel('Dates')
plt.ylabel('Transactions')
plt.show()

我的CSV内容如下:

2022-08-25,1
2022-08-26,2
2022-08-27,4
2022-08-29,3

修复方案

如果需要折线按交易数值1→2→3→4的顺序展示,可按以下方式修改代码:

  1. 将读取的交易数值转为整数类型,确保能进行数值排序
  2. 把日期和交易数值配对成元组,按交易数值升序排序
  3. 拆分排序后的日期与数值列表再绘图

修改后的代码:

import csv
import matplotlib.pyplot as plt

data = []
  
with open('new.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter = ',')
    for row in plots:
        data.append((row[0], int(row[1])))

# 按交易数值升序排序
data.sort(key=lambda x: x[1])

time = [item[0] for item in data]
total = [item[1] for item in data]
  
plt.plot(time, total)
plt.xlabel('Dates')
plt.ylabel('Transactions')
plt.show()

如果需求是保持原日期顺序,仅需修复数值类型问题(当前读取的是字符串,可能导致绘图逻辑异常),修改读取数值的代码即可:

import csv
import matplotlib.pyplot as plt

time = []
total = []
  
with open('new.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter = ',')
    for row in plots:
        time.append(row[0])
        total.append(int(row[1]))
  
plt.plot(time, total)
plt.xlabel('Dates')
plt.ylabel('Transactions')
plt.show()

内容的提问来源于stack exchange,提问作者Boby

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:42:28