如何将ggplot2中scale_x_time的X轴格式改为HH:MM而非HH:MM:SS
解决ggplot2 X轴时间格式(HH:MM)问题
问题说明
现有数据结构如下:
| Price | Seconds | Date |
|---|---|---|
| 11111 | 6443 | 2022-01-03 |
| 22222 | 7400 | 2022-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
相关产品推荐
相关产品推荐

