matplotlib连接datetime时间散点未设时区却报tz类型错误怎么办
报错核心原因
你连线的调用逻辑从参数配对上就出现了本质错误。
你绘制散点时的坐标规则是:
- x轴为日期类型数据
- y轴为文本类型的handler标识
两个散点对,是同一个handler对应的两个不同日期值,y值完全相同。
但你之前调用plt.plot()、plt.plot_date()时,直接把两个一维日期列表分别当成x参数、y参数传入:
# 错误的调用逻辑 plt.plot(first_test, handler_arrive, '-o') plt.plot_date(first_test, handler_arrive)
这种传参方式下,matplotlib会默认把第二个传入的handler_arrive列表解析为y轴序列。而你的y轴本身是文本类的handler标签,内部靠UnitData完成刻度映射,收到datetime类型的输入值时会自动触发时区转换逻辑,最终抛出TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'UnitData'的报错——这和你是否设置过时区参数没有关系,哪怕传tz=None也解决不了参数错位的问题。
正确的连线实现逻辑
连线需要按每个handler的两个散点坐标逐一配对,也就是对每一组数据:
- 连线起点:坐标为
(handler_arrive[i], handlers[i]),对应蓝色圆点位置 - 连线终点:坐标为
(first_test[i], handlers[i]),对应橙色圆点位置
不需要逐点单独调用绘图接口,只要把所有连线的坐标按顺序拼合成两个一维列表,一次调用plot即可完成所有横向连线的绘制。
可直接运行的完整示例代码:
import datetime as dt import matplotlib.pyplot as plt # 原始数据 handlers = [ "hvvm-02", "hvvm-03", "hvvm-04", "hvvm-07", "hvvm-09", "hvvm-10", "hvvm-11", "hvvm-12" ] first_test_str = [ "7/15/2020", "4/8/2020", "5/27/2020", "7/8/2020", "2/26/2020", "2/26/2020", "7/1/2020", "7/15/2020" ] handler_arrive_str = [ "1/26/2020", "1/26/2020", "1/26/2020", "1/26/2020", "1/7/2020", "1/7/2020", "1/6/2020", "1/6/2020" ] # 日期格式转换 first_test = [dt.datetime.strptime(date, '%m/%d/%Y').date() for date in first_test_str] handler_arrive = [dt.datetime.strptime(date, '%m/%d/%Y').date() for date in handler_arrive_str] # 初始化画布 fig, ax = plt.subplots(figsize=(10, 6)) # 绘制两类散点 ax.scatter(first_test, handlers, c='tab:orange', label='首次测试日期') ax.scatter(handler_arrive, handlers, c='tab:blue', label='人员抵达日期') # 拼接所有连线的坐标序列 line_x = [] line_y = [] for arrive_date, test_date, handler in zip(handler_arrive, first_test, handlers): line_x.extend([arrive_date, test_date]) line_y.extend([handler, handler]) # 绘制灰色连线,设置zorder让连线位于散点下层 ax.plot(line_x, line_y, c='gray', zorder=0) # 优化图表显示 fig.autofmt_xdate() ax.legend() plt.tight_layout() plt.show()
补充说明
- 不需要单独调用
plot_date接口,matplotlib的plot方法本身就支持datetime类型的x轴输入,只要参数配对正确即可正常渲染 - 绘图时可以通过调整
zorder参数,保证连线显示在散点图形的下层,不会遮挡圆点标记
内容的提问来源于stack exchange,提问作者Glenn Oberlander
相关产品推荐
相关产品推荐

