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

将Time列设为x轴刻度时Seaborn绘图报错的问题求助

Let's break down what went wrong and fix this step by step.

Why you got the TypeError

When you tried plt.xticks(ticks=t), you misunderstood what the ticks parameter expects. The ticks argument needs numeric positions (like row indices) corresponding to where you want labels placed on the x-axis. But you passed an array of time strings (t), and Seaborn was using the underlying numeric indices of your DataFrame as the x-axis positions. Comparing these numeric indices to your string values triggered the < not supported error.

Also, your first plot had wonky x-axis ticks because your Time column was stored as an object (string) type. Seaborn treats string columns as categorical variables, not continuous time, so it arranged ticks based on string alphabetical order instead of actual time sequence.

Fix 1: Convert Time to datetime (the cleanest approach)

The best solution is to convert your Time column to a proper datetime type. This lets Seaborn and Matplotlib recognize it as a continuous time axis, which handles tick ordering and formatting correctly automatically.

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

# Convert Time column to datetime format
w_df['Time'] = pd.to_datetime(w_df['Time'], format='%H:%M:%S')

# Plot using the datetime column directly
sns.lineplot(x="Time", y="Samstag", data=w_df)

# Rotate ticks and set the display format to HH:MM:SS
plt.xticks(rotation=15)
plt.gca().xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%H:%M:%S'))

plt.xlabel("Time")
plt.ylabel("KWH")
plt.show()

Fix 2: Manual tick positions and labels (if you need more control)

If you want to explicitly set every time value as a tick (instead of letting Matplotlib sample), you can use the DataFrame's row indices as tick positions, and your formatted time strings as labels:

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

# Keep the original Time column, but create a formatted string version
w_df['Time_formatted'] = pd.to_datetime(w_df['Time'], format='%H:%M:%S').dt.strftime('%H:%M:%S')

# Plot using the row index as the x-axis (so we can map ticks to positions)
sns.lineplot(x=w_df.index, y="Samstag", data=w_df)

# Set ticks to row indices, labels to your formatted time strings
plt.xticks(ticks=w_df.index, labels=w_df['Time_formatted'], rotation=15)

plt.xlabel("Time")
plt.ylabel("KWH")
plt.show()

Key Takeaway

Always convert time-based columns to datetime types when working with time-series plots. This avoids categorical ordering issues and lets visualization libraries handle time logic correctly without manual hacks.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 22:22:30