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

如何在Seaborn Swarmplot中正确绘制DatetimeIndex的时间维度

解决Seaborn Swarmplot时间轴无序问题

你的问题出在datetime.time类型被Seaborn当作字符串处理,字符串排序是按字符顺序而非时间逻辑顺序,导致X轴乱序。下面提供两种可行的解决方法:

方法一:用时间戳数值做x轴(推荐)

将时间转换为一天中的秒数作为数值型x轴,再替换刻度标签为时间格式,既保证排序正确,又不影响可视化效果:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

# 修正原代码语法错误(补全逗号)并读取数据
on_times = pd.read_csv(
    "fridge_freezer_on.csv",
    parse_dates=["local_updated"],
    index_col="local_updated"
)

on_times["Day"] = on_times.index.strftime("%a")
# 计算时间对应的一天内秒数,用于排序
on_times["Time_seconds"] = on_times.index.hour * 3600 + on_times.index.minute * 60 + on_times.index.second
# 保留原时间格式用于刻度标签
on_times["Time"] = on_times.index.time

fig, ax = plt.subplots()
# 用秒数作为x轴,确保排序正确
sns.swarmplot(data=on_times, x="Time_seconds", y="Day", hue="id", ax=ax)

# 自定义x轴刻度,替换为易读的时间字符串
tick_positions = [0, 3600*6, 3600*12, 3600*18, 3600*23+59*60+59]
tick_labels = ["00:00:00", "06:00:00", "12:00:00", "18:00:00", "23:59:59"]
ax.set_xticks(tick_positions)
ax.set_xticklabels(tick_labels)
ax.set_xlabel("Time")

plt.show()

方法二:将Time列转为datetime64类型

给时间拼接固定日期,转为datetime64类型,让Seaborn自动识别时间顺序,最后隐藏日期部分:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

on_times = pd.read_csv(
    "fridge_freezer_on.csv",
    parse_dates=["local_updated"],
    index_col="local_updated"
)

on_times["Day"] = on_times.index.strftime("%a")
# 拼接固定日期,转为datetime64类型
on_times["Time"] = pd.to_datetime("2020-01-01 " + on_times.index.strftime("%H:%M:%S"))

fig, ax = plt.subplots()
sns.swarmplot(data=on_times, x="Time", y="Day", hue="id", ax=ax)

# 格式化x轴,只显示时间部分
ax.xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter("%H:%M:%S"))
plt.xticks(rotation=45)  # 旋转标签避免重叠

plt.show()

注意

原代码中parse_dates=["local_updated"]后缺少逗号,会导致语法错误,上述代码已修正该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 14:15:21