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

如何用R语言ggplot2为折线图添加指定数据点

实现方法

你需要先将两个数据集中的日期和小时字段合并为连续的时间格式,避免X轴顺序错乱,再在折线图层上叠加散点图层即可,完整实现代码如下:

# 加载所需包
library(ggplot2)
library(lubridate) # 用于时间格式处理,无该包可改用下方base R方法处理时间

# 合并日期、小时为统一的时间列
mytransaction.plot$datetime <- ymd_h(paste(mytransaction.plot$datex, mytransaction.plot$hourx))
mytransaction.dot$datetime <- ymd_h(paste(mytransaction.dot$datex, mytransaction.dot$hourx))

# 绘制目标图形
ggplot() +
  # 绘制全量数据折线
  geom_line(data = mytransaction.plot, aes(x = datetime, y = transaction), linewidth = 0.8, color = "grey20") +
  # 叠加指定数据的圆点层,参数可按需调整样式
  geom_point(data = mytransaction.dot, aes(x = datetime, y = transaction), size = 3, color = "red", fill = "orange", shape = 21) +
  # 优化X轴时间显示
  scale_x_datetime(date_labels = "%m-%d %H:%M", date_breaks = "12 hours") +
  labs(x = "时间", y = "交易量") +
  theme_bw()

如果不想额外安装lubridate包,可改用base R的方法处理时间列:

mytransaction.plot$datetime <- as.POSIXct(paste(mytransaction.plot$datex, mytransaction.plot$hourx), format = "%Y-%m-%d %H")
mytransaction.dot$datetime <- as.POSIXct(paste(mytransaction.dot$datex, mytransaction.dot$hourx), format = "%Y-%m-%d %H")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:21:01