R语言Shiny Dashboard中基于波动率滑块生成投资组合权重动态饼图
解决方案
核心修改点
- 调整
sliderValues响应式函数的返回值,将原本的字符串输出改为数值向量,方便提取前3项资产权重 - UI端新增饼图输出容器
- 新增饼图渲染逻辑,绑定滑块的动态数值
完整修改后代码
library(shiny) library(dplyr) # 若原本未加载dplyr请保留该行 # UI部分 ui <- fluidPage( headerPanel(title = "Volatility Slider"), sidebarLayout( sidebarPanel( sliderInput("Risk","Volatility", 0, 0.24, 0.12) ), mainPanel( textOutput("Output"), # 新增饼图输出位 plotOutput("pieChart") ) ) ) # 服务端部分 server <- function(input, output) { sliderValues <- reactive({ custom <- three_assets %>% filter(sd_p > input$Risk, sd_p < input$Risk+0.0001) max_er_custom <- custom[custom$er_p == max(custom$er_p), ] # 改为返回数值向量,不要转字符串 as.numeric(max_er_custom) }) output$Output <- renderText({ # 文本输出优化为易读格式 paste("股票权重:", round(sliderValues()[1]*100,2), "%,", "黄金权重:", round(sliderValues()[2]*100,2), "%,", "白银权重:", round(sliderValues()[3]*100,2), "%,", "预期收益率:", round(sliderValues()[4]*100,2), "%,", "波动率:", round(sliderValues()[5]*100,2), "%") }) # 新增饼图渲染逻辑 output$pieChart <- renderPlot({ weights <- sliderValues()[1:3] labels <- c("股票", "黄金", "白银") # 基础R绘图实现 pie(weights, labels = paste0(labels, ": ", round(weights*100, 2), "%"), col = c("#2E86AB", "#A23B72", "#F18F01"), main = "最优投资组合资产权重分布") # 若需用ggplot2绘制更美观的饼图,注释掉上面的pie代码,启用下方代码即可 # library(ggplot2) # df <- data.frame(asset = labels, weight = weights) # ggplot(df, aes(x="", y=weight, fill=asset)) + # geom_bar(stat="identity", width=1) + # coord_polar("y", start=0) + # labs(title = "最优投资组合资产权重分布", fill = "资产类别") + # theme_void() + # geom_text(aes(label = paste0(round(weight*100,2),"%")), position = position_stack(vjust = 0.5)) }) } # 运行应用 shinyApp(ui = ui, server = server)
注意事项
请确保three_assets数据集的列顺序符合前3列为股票、黄金、白银权重,第4、5列分别为预期收益率、波动率,否则需要调整数值提取的索引顺序。
内容的提问来源于stack exchange,提问作者Olav3D
相关产品推荐
相关产品推荐

