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

如何用R语言的Plotly制作带悬停信息的时间动画折线图

R中用Plotly实现随时间推进的折线动画(支持悬停)

核心实现思路

借助Plotly的frame参数实现时间维度的动画推进,通过生成累积数据让折线逐步绘制,同时自定义悬停文本展示数据点的时间和功率详情。

完整代码

# 加载依赖包
library(plotly)
library(dplyr)

# 模拟你的数据集(若已有pv1_table可直接使用)
pv1_table <- tibble(
  Date_Time = as.POSIXct(c("2023-06-09 15:26:55", "2023-06-09 15:26:59", 
                           "2023-06-09 15:27:02", "2023-06-09 15:27:05", 
                           "2023-06-09 15:27:09", "2023-06-09 15:27:12")),
  Total.Active.Power = c(0.5, 0.5, 1.0, 1.5, 0.5, 2.0)
)

# 生成动画所需的累积数据(每个帧对应到当前时间点的所有历史数据)
animated_data <- pv1_table %>%
  mutate(frame = row_number()) %>%
  group_by(frame) %>%
  summarise(
    Date_Time = list(Date_Time[1:frame]),
    Total.Active.Power = list(Total.Active.Power[1:frame]),
    hover_text = list(paste("时间:", Date_Time[1:frame], "<br>有功功率:", Total.Active.Power[1:frame]))
  ) %>%
  ungroup()

# 创建Plotly动画图
plot_ly(animated_data) %>%
  add_lines(
    x = ~Date_Time, 
    y = ~Total.Active.Power, 
    color = I("blue"), 
    size = I(2),
    frame = ~frame,  # 指定动画推进的帧
    hoverinfo = "text", 
    text = ~hover_text  # 自定义悬停显示内容
  ) %>%
  layout(
    xaxis = list(title = "时间"),
    yaxis = list(title = "总有功功率")
  ) %>%
  animation_slider(currentvalue = list(prefix = "当前时间: ")) %>%  # 滑块显示当前时间前缀
  animation_button(label = "播放")  # 自定义播放按钮文本

关键细节说明

  • 累积数据逻辑:通过row_number()生成帧序号,每个帧仅保留到当前时间点的所有数据,实现折线随时间逐步延长的效果
  • 悬停配置:预先拼接好包含时间和功率的格式化文本,通过hoverinfo="text"让鼠标悬停时展示完整数据详情
  • 动画控件:animation_slider和animation_button分别生成进度滑块与播放按钮,优化交互体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:38:35