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

ggplot2按强度区间给24小时心率折线着色及NA值显示异常求助

问题原因与解决方案

跨区间直线问题

  • 触发原因:geom_line()默认以颜色映射的intensity作为分组依据,所有属于同一强度的点无论间隔多久都会被直线连接,跨区间的异常连线就是不同时间段的同强度点被直接连接导致的。
  • 修复方案:为每一段连续的同强度区间生成独立分组ID,让线条仅连接同一连续段内的点。

NA值仍显示问题

  • 触发原因:
    1. na.rm=TRUE参数放在了全局美学映射aes()中,不属于美学映射配置的参数不会生效,需要配置在geom_line()的参数列表中。
    2. 同时使用ylim()和scale_y_continuous()设置Y轴产生冲突,ylim()会强制将超出范围的数值转为NA,还会干扰空值过滤逻辑。
  • 修复方案:
    1. 将na.rm=TRUE移至geom_line()参数中。
    2. 删除冗余的ylim()配置,将Y轴范围写入scale_y_continuous()的limits参数。
修改后可运行代码
library(tidyverse)
library(hms)
library(dplyr)
library(lubridate)
library(ggplot2)

# 导入数据集
graph <-read.csv("graph.csv", sep=";", na.strings = "?")
graph$HR <- as.numeric(as.character(graph$HR))
graph$Zone <- as.numeric(as.character(graph$Zone))
graph$Time =as.POSIXct(graph$Time,format="%H:%M:%S") 
graph$Time = as_hms(graph$Time) 

# 生成强度因子与连续段分组ID
graph$intensity<-factor(graph$Intensity, 
                    levels =c("Sedentary", "Light", "Moderate", "Vigorous"))
graph <- graph %>%
  mutate(segment_id = cumsum(intensity != lag(intensity, default = first(intensity))))

# 绘图
ggplot(graph, aes(x = Time, y = HR, color = intensity, group = segment_id)) +
  geom_line(na.rm=TRUE) +
  labs(x = "Time", y = "Heart Rate (bpm)")+
  scale_color_discrete("Intensity:", labels = c("Sedentary", "Light",
                                              "Moderate", "Vigorous")) +
  theme(legend.title = element_text(family = "Playfair",
                                    color = "chocolate",
                                    size = 10, face = 2))+
  theme(panel.grid = element_blank()) +
  geom_rug(show.legend = FALSE)+
  scale_x_datetime(date_breaks = "4 hours", date_labels = "%H:%M")+
  scale_y_continuous(breaks = seq(0, 160, by =40), limits = c(0,160))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:15:01