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

如何在ggplot2中修改scale_y_time()生成的轴标签为%M:%S格式

调整ggplot2 scale_y_time轴标签为分:秒格式的方法

你只需要调整scale_y_time()的labels参数,搭配scales包提供的时间格式化函数即可实现需求,完整可运行的修改后代码如下:

library(tidyverse)

start <- seq(1, 105, 5)
end <- seq(3, 103, 5)
time = seq(0, 360, 18)

dat <- data.frame(start, end, time)

ggplot(dat) + 
  geom_segment(aes(x = start, y = time, xend = end, yend = time)) +
  # 仅修改这一行即可
  scale_y_time(labels = scales::time_format("%M:%S"))

补充说明

  • scales是ggplot2的内置依赖包,安装tidyverse时会同步安装,无需额外下载
  • time_format()传入的%M:%S为时间格式化字符串,其中%M代表分钟、%S代表秒,符合基础的展示规则
  • 如果你需要处理超过1小时的时长、且需要展示累计总分钟数(例如75秒显示为01:15、4000秒显示为66:40而非01:06:40),可以使用自定义格式化函数,写法如下:
ggplot(dat) + 
  geom_segment(aes(x = start, y = time, xend = end, yend = time)) +
  scale_y_time(
    labels = function(x) {
      total_sec <- as.numeric(x)
      sprintf("%02d:%02d", floor(total_sec/60), total_sec %% 60)
    }
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:45:02