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

如何将ggplot2中scale_x_time的X轴格式改为HH:MM而非HH:MM:SS

解决ggplot2 X轴时间格式(HH:MM)问题

问题说明

现有数据结构如下:

PriceSecondsDate
1111164432022-01-03
2222274002022-01-04

使用以下ggplot2代码绘图时,X轴时间默认显示为HH:MM:SS格式,希望调整为仅显示HH:MM:

ggplot(data=d.2,aes(x=Seconds, y=Price)) + 
  geom_path(colour="blue") + 
  ylab("Price") + 
  xlab("Date") +
  coord_cartesian(xlim = c(7*3600+5*60, 15*3600+25*60)) +
  facet_wrap(~Date, nrow = 1) +
  scale_x_time()

解决方案

在scale_x_time()中通过labels参数指定时间格式为%H:%M,需要用到scales包的time_format()函数(未安装的话先运行install.packages("scales"))。修改后的代码如下:

library(scales) # 加载scales包

ggplot(data=d.2,aes(x=Seconds, y=Price)) + 
  geom_path(colour="blue") + 
  ylab("Price") + 
  xlab("Date") +
  coord_cartesian(xlim = c(7*3600+5*60, 15*3600+25*60)) +
  facet_wrap(~Date, nrow = 1) +
  scale_x_time(labels = time_format("%H:%M"))

补充说明

  • time_format("%H:%M")会将时间值直接格式化为小时:分钟形式,自动剔除秒数部分
  • 若需要12小时制(带上午/下午标记),可改用格式字符串%I:%M %p

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 01:39:54