如何在Matplotlib中设置x轴时分刻度、固定间隔并将12:00居中?
问题修复方案
1. 时间格式转换报错解决
你遇到的TypeError: <class 'datetime.time'> is not convertible to datetime报错,是因为Excel读取后time列已经是datetime.time类型,你调用pd.to_datetime()后额外取了.dt.date,会直接丢弃时分秒信息,完全不符合时间轴展示需求。
仅需将时间列统一绑定到同一个虚拟日期上(日期不影响展示,仅保留时间维度的对比关系),同时自动识别12小时制带AM/PM的时间格式即可:
df3["time"] = pd.to_datetime(df3["time"])
2. X轴刻度调整与12:00居中配置
要让12:00处于x轴正中心,直接把x轴的显示范围固定为当日6:00到18:00即可,总跨度12小时的情况下12:00自然居中,再手动指定你需要的2小时间隔刻度即可,完整可运行代码如下:
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from matplotlib.dates import HourLocator, DateFormatter df3 = pd.read_excel(r'results.xlsx') # 修复时间列转换逻辑 df3["time"] = pd.to_datetime(df3["time"]) # 基础绘图 color = 'black' ax1 = sns.lineplot(x = 'time', y = 'parabolic', data = df3, color = color, label='Light intensity') ax2 = ax1.twinx() ax2 = sns.scatterplot(x = 'time', y = 'Gas-exchange_p', hue= 'Sampling', marker='v', s=200, data = df3, label= 'Measurement time points') # 固定x轴范围为6:00-18:00,实现12:00居中 base_day = df3["time"].dt.floor('D').iloc[0] ax1.set_xlim(base_day + pd.Timedelta(hours=6), base_day + pd.Timedelta(hours=18)) # 设置x轴刻度:间隔2小时,显示格式为HH:MM ax1.xaxis.set_major_locator(HourLocator(interval=2)) ax1.xaxis.set_major_formatter(DateFormatter('%H:%M')) # 合并双轴图例避免丢失 lines1, labels1 = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax1.legend(lines1 + lines2, labels1 + labels2, loc="upper right") # 隐藏右侧轴默认图例避免重复 ax2.get_legend().remove() plt.show()
内容的提问来源于stack exchange,提问作者Martina Lazzarin
相关产品推荐
相关产品推荐

