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

如何在ggplot2中按时间顺序绘图并将数值DAS设为X轴标签

问题描述

现有如下数据框:

df <- data.frame( 
  Time = as.POSIXct(c("2023-08-01 08:00:00", "2023-08-01 12:00:00",
                      "2023-08-05 08:00:00", "2023-08-05 12:00:00",
                      "2023-08-10 08:00:00", "2023-08-10 12:00:00",
                      "2023-08-15 08:00:00", "2023-08-15 12:00:00")),  
  DAS = c(0, 0, 4, 4, 9, 9, 14, 14), 
  emmean = c(10, 15, 20, 25, 30, 35, 40, 45) 
)

需要按时间顺序绘制数据(保留POSIXct格式),同时将数值型DAS值作为X轴标签,要求每个日期仅显示一个DAS值,且断点频率为1天。

已尝试两种方案,但都存在问题:

  • 方案1:使用scale_x_continuous,每个时间点重复显示DAS标签
    p <- ggplot(df, aes(x = Time, y = emmean)) + geom_point()
    p + scale_x_continuous(breaks = df$Time, labels = df$DAS)
    
  • 方案2:使用scale_x_datetime,仍显示日期而非DAS值
    p + scale_x_datetime(breaks = df$Time, labels = df$DAS, date_breaks = "1 day", date_labels = "%b %d")
    
解决方案

核心是先提取每个日期对应的唯一DAS值,再在scale_x_datetime中指定对应断点和标签:

方法1(使用dplyr)

library(ggplot2)
library(dplyr)

# 创建包含唯一日期和对应DAS值的辅助数据框
date_das <- df %>%
  mutate(Date = as.Date(Time)) %>%
  distinct(Date, DAS)

# 绘图并设置X轴
p <- ggplot(df, aes(x = Time, y = emmean)) + geom_point()

p + scale_x_datetime(
  breaks = as.POSIXct(date_das$Date),  # 断点设为每个唯一日期
  labels = date_das$DAS,              # 对应显示DAS值
  expand = c(0.05, 0)                 # 可选:调整轴范围避免点贴边
)

方法2(基础R实现,无需dplyr)

library(ggplot2)

# 创建辅助数据框
df$Date <- as.Date(df$Time)
date_das <- unique(df[, c("Date", "DAS")])

# 绘图并设置X轴
p <- ggplot(df, aes(x = Time, y = emmean)) + geom_point()

p + scale_x_datetime(
  breaks = as.POSIXct(date_das$Date),
  labels = date_das$DAS,
  expand = c(0.05, 0)
)

说明

  • 通过as.Date(Time)提取日期部分,确保每个日期仅保留一个断点,避免重复标签。
  • 将日期转换为POSIXct格式,匹配X轴的时间类型。
  • 直接用date_das$DAS作为标签,每个断点对应唯一的DAS值,完美匹配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:47:25