Python3生成等长有序序列解决绘图X轴时间显示异常问题
Python绘制温度时序图X轴刻度异常解决方案
问题描述
需要在Python3环境中生成与目标列表长度一致的有序数字序列,已编写如下CSV解析函数提取文件中的时间、温度数据:
def parse_data_from_file(filename): times = [] temperatures = [] with open(filename) as csvfile: reader = csv.reader(csvfile, delimiter=',') next(reader) for row in reader: times.append(row[0]) temperatures.append(float(row[1])) return times, temperatures
使用上述代码解析得到的数据绘制图表时,X轴时间刻度显示重叠、无法正常识别,异常效果如下:
问题原因
解析得到的times列表存储的是字符串类型值,matplotlib会将每个字符串识别为独立分类刻度,数据量较大时所有刻度会挤在一起重叠,无法正常展示。
解决方案
方案1:生成有序数字序列作为X轴坐标,手动控制刻度显示
直接通过range()生成与数据长度一致的有序数字序列作为X轴位置占位,再间隔选取时间字符串设置为刻度标签,从根源避免刻度拥挤。
import matplotlib.pyplot as plt # 读取解析后的数据 times, temperatures = parse_data_from_file("你的数据文件.csv") # 生成和数据长度匹配的有序数字序列 x_pos = list(range(len(times))) plt.figure(figsize=(10, 6)) plt.plot(x_pos, temperatures) # 间隔设置刻度,步长可根据数据总量调整,比如每10个点显示1个刻度 plt.xticks( ticks=x_pos[::10], labels=times[::10], rotation=45 # 刻度文字旋转45度,避免文字重叠 ) # 自动调整布局,防止刻度被画布边缘截断 plt.tight_layout() plt.show()
方案2:将时间字符串转为datetime类型,自动适配时间轴
修改CSV解析逻辑,把时间字符串转为Python原生datetime对象,matplotlib可自动识别时间类型、适配刻度间隔,更适合规范的时间序列数据。
from datetime import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates # 修改原解析函数,增加时间字符串转datetime逻辑 def parse_data_from_file(filename): times = [] temperatures = [] with open(filename) as csvfile: reader = csv.reader(csvfile, delimiter=',') next(reader) for row in reader: # 注意strptime的格式符要和CSV内的时间格式匹配 # 例:时间为"2024-05-01 08:30"则格式为"%Y-%m-%d %H:%M" time_obj = datetime.strptime(row[0], "%Y-%m-%d %H:%M") times.append(time_obj) temperatures.append(float(row[1])) return times, temperatures times, temperatures = parse_data_from_file("你的数据文件.csv") plt.figure(figsize=(10,6)) plt.plot(times, temperatures) # 设置时间刻度显示格式与间隔 plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%m-%d %H:%M")) plt.gca().xaxis.set_major_locator(mdates.HourLocator(interval=2)) plt.xticks(rotation=45) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者zille_elahi
相关产品推荐
相关产品推荐

