R Shiny Web应用中gganimate生成的Animated Bar Plot无法显示
R Shiny展示gganimate动态条形图的修复方案
你代码中存在4个可直接导致动图无法显示的问题:
- 输出ID不匹配:UI层
plotOutput绑定的id为myplot,服务端输出的对象名为plot,二者不一致无法触发渲染 - 渲染组件不匹配:
gganimate生成的是GIF格式动图,不能使用Shiny默认的静态图渲染组合renderPlot+plotOutput,需替换为动图适配的renderImage+imageOutput - 大小写语法错误:启动应用的
shinyApp函数第一个参数写为大写UI,但实际定义的UI对象是小写ui,R对大小写敏感会直接报错 - 图层逻辑错误:添加标题的图层操作没有赋值回
undergrad_plot对象,最终生成的动画会丢失你配置的标题样式
以下是修正后可直接运行的完整代码:
# 加载依赖库 library(ggplot2) library(shiny) library(gganimate) # 读取数据 undergradDATA <- read.csv(file="1-10 Undergraduates.csv", head=TRUE, sep=",") # UI定义 ui <- fluidPage ( mainPanel( # 替换为动图专用的imageOutput,绑定id为myplot imageOutput("myplot") ) ) # 服务端定义 server <- function(input, output) { output$myplot <- renderImage({ # 合并图层配置,避免赋值丢失 undergrad_plot <- ggplot(data=undergradDATA , aes(x=HEI, y=Undergrad)) + geom_bar(stat='identity', fill="darkolivegreen3", colour="white") + ggtitle("Ranking of Top 10 HEI's w.r.t Undergraduates") + theme( plot.title = element_text(hjust = 0.5, colour = "darkolivegreen", size = 17, family = "courier" ) ) + # 追加动画配置 transition_states(Undergrad, wrap = FALSE) + shadow_mark() + enter_grow() + enter_fade() # 生成动图临时文件 anim <- animate(undergrad_plot, width = 644, height = 461) tmp_file <- tempfile(fileext = ".gif") anim_save(tmp_file, animation = anim) # 返回动图资源给前端 list(src = tmp_file, contentType = "image/gif", width = 644, height = 461, alt = "高校本科生人数排名动态条形图") }, deleteFile = TRUE) # 渲染完成后自动删除临时文件,避免占用磁盘空间 } # 启动应用,参数使用小写ui和定义的server对象 shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者Aqsa Hafeez
相关产品推荐
相关产品推荐

