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

Matplotlib:在散点图的Y轴设置整点刻度

解决散点图Y轴整点刻度显示问题

我明白你想要的效果——让Y轴只显示指定的整点刻度,而不是密密麻麻的每小时刻度。之前用HourLocator的方法失效,是因为df.index.time返回的是datetime.time对象,而matplotlib的日期定位器是为完整的datetime64类型设计的,直接处理time对象会出现兼容问题。

这里有两种简单有效的解决方案:

方法一:手动指定Y轴刻度位置与标签

这种方法直接定义你想要显示的整点,把它们转换成matplotlib能识别的数值(一天的时间被映射为0-1的区间,0对应00:00,1对应24:00),然后设置刻度:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FixedLocator, FixedFormatter

# 你的数据(补充了一些示例数据让效果更明显)
Time = ['2018-03-16 16:15', '2018-03-16 16:30', '2018-03-16 16:45',
        '2018-03-17 07:20', '2018-03-17 07:40', '2018-03-18 12:10',
        '2018-03-18 19:30']
Speed = [56, 46, 51, 22, 18, 45, 30]

df = pd.DataFrame({'Time':pd.to_datetime(Time), 'Speed':Speed})
df.set_index('Time', inplace=True)

fig, ax = plt.subplots()
# 散点图:X轴是完整日期时间,Y轴是一天中的时段,点大小对应速度
ax.scatter(df.index, df.index.time, s=df['Speed']*5, alpha=0.7)

# 定义你想显示的整点时刻
target_hours = [6, 12, 16, 20]
# 转换为matplotlib的Y轴数值(0-1区间)
tick_positions = [hour/24 for hour in target_hours]
# 生成对应的刻度标签
tick_labels = [f"{hour:02d}:00" for hour in target_hours]

# 应用刻度设置
ax.yaxis.set_major_locator(FixedLocator(tick_positions))
ax.yaxis.set_major_formatter(FixedFormatter(tick_labels))

# 设置X、Y轴范围
ax.set_xlim('2018-03-04','2018-03-31')
ax.set_ylim(6/24, 20/24)

fig.autofmt_xdate()
plt.show()

方法二:将时间转换为小时数值处理

把一天中的时段转换成小时数(比如16:15变成16.25),这样Y轴就变成数值轴,更容易控制刻度:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FixedLocator, FixedFormatter

Time = ['2018-03-16 16:15', '2018-03-16 16:30', '2018-03-16 16:45',
        '2018-03-17 07:20', '2018-03-17 07:40', '2018-03-18 12:10',
        '2018-03-18 19:30']
Speed = [56, 46, 51, 22, 18, 45, 30]

df = pd.DataFrame({'Time':pd.to_datetime(Time), 'Speed':Speed})
# 将时间转换为小时数值(小时+分钟/60)
df['HourOfDay'] = df['Time'].dt.hour + df['Time'].dt.minute/60

fig, ax = plt.subplots()
ax.scatter(df['Time'], df['HourOfDay'], s=df['Speed']*5, alpha=0.7)

# 设置Y轴刻度
target_hours = [6, 12, 16, 20]
ax.yaxis.set_major_locator(FixedLocator(target_hours))
ax.yaxis.set_major_formatter(FixedFormatter([f"{h:02d}:00" for h in target_hours]))

# 设置轴范围
ax.set_xlim('2018-03-04','2018-03-31')
ax.set_ylim(6, 20)

fig.autofmt_xdate()
plt.show()

两种方法都能精准控制Y轴只显示你需要的整点刻度,你可以根据自己的习惯选择其中一种。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:48:08