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

如何在R的Plotly中制作随时间变化的环形动画图表

实现随时间动态变化的环形图(Donut Chart)

要让环形图的切片长度随Date_Time对应的TOTAL_ENERGY值动态变化,可利用plotly的**动画帧(frame)**功能实现,具体步骤如下:

步骤1:预处理数据

先将Date_Time转换为时间类型,确保动画能按时间顺序播放:

library(tibble)
library(plotly)

# 原始数据
data <- tibble(
  asset_name = c("PCC", "PCC", "PCC", "PCC", "PCC", "PCC", "pv", "pv", "pv", "pv", "pv", "pv"),
  Date_Time = c("2023-06-14 09:43:19", "2023-06-14 09:43:22", "2023-06-14 09:43:26",
                "2023-06-14 09:43:29", "2023-06-14 09:43:33", "2023-06-14 09:43:36",
                "2023-06-14 09:43:19", "2023-06-14 09:43:22", "2023-06-14 09:43:26",
                "2023-06-14 09:43:29", "2023-06-14 09:43:33", "2023-06-14 09:43:36"),
  PCC_ENERGY_IMPORTED = c(187081, 187081, 187081, 187081, 187082, 187082, 0, 0, 0, 0, 0, 0),
  PV_ENERGY_PRODUCED = c(0, 0, 0, 0, 0, 0, 3425.746, 3425.746, 3425.746, 3425.769, 3425.769, 3425.769),
  TOTAL_ENERGY = c(187081, 187081, 187081, 187081, 187082, 187082, 3425.746, 3425.746, 3425.746, 3425.769, 3425.769, 3425.769)
)

# 转换Date_Time为时间类型
data$Date_Time <- as.POSIXct(data$Date_Time)

步骤2:绘制动态环形图

在plot_ly中通过frame参数绑定时间维度,实现切片随时间动态变化:

plot <- plot_ly(
  data,
  labels = ~asset_name,
  values = ~TOTAL_ENERGY,
  type = "pie",
  hole = 0.5,
  text = ~paste("总能量:", TOTAL_ENERGY),
  textinfo = "text",
  hoverinfo = "label+value",
  frame = ~Date_Time,  # 绑定时间维度作为动画帧
  ids = ~asset_name    # 确保每个asset在帧间保持对应样式
)

# 自定义布局与动画控制
plot <- plot %>%
  layout(
    title = "能量贡献随时间变化",
    showlegend = TRUE,
    legend = list(x = 1, y = 0.5),
    updatemenus = list(
      list(
        type = "buttons",
        showactive = FALSE,
        buttons = list(
          list(label = "播放",
               method = "animate",
               args = list(NULL, list(frame = list(duration = 500, redraw = TRUE),
                                     fromcurrent = TRUE))),
          list(label = "暂停",
               method = "animate",
               args = list(list(frame = list(duration = 0, redraw = FALSE)),
                           list(mode = "immediate")))
        )
      )
    )
  ) %>%
  animation_slider(
    currentvalue = list(prefix = "当前时间: ", font = list(size = 12))
  )

plot

关键参数说明

  • frame = ~Date_Time:将每个时间点作为独立动画帧,环形图会根据对应时间点的TOTAL_ENERGY更新切片长度
  • ids = ~asset_name:保证不同帧中同一asset的切片样式一致,避免动画跳转混乱
  • animation_slider:添加时间滑块,可手动切换任意时间点的环形图状态
  • 按钮控制:添加播放/暂停按钮,方便控制动画节奏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:26:58