首页 > 解决方案 > R中的动态饼图使用闪亮的仪表板

问题描述

我目前正在研究一个闪亮的仪表板,它有一个滑块,使用滑块输入输出给定波动率值的股票、黄金和白银的最佳投资组合权重。在给定滑块输入的情况下,我已经能够通过动态文本输出输出值,但我无法弄清楚如何将这些值转换为图形,因为 Shiny 中的文本输出似乎需要一个函数。如何使用从中获得的值向此代码添加饼图slidervalues()?它输出 5 个数值的列表,现在我想在饼图中绘制前 3 个数值:

library(shiny)
shinyUI(fluidPage(
  headerPanel(title = "Volatility Slider"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("Risk","Volatility", 0, 0.24, 0.12)
    ),
    mainPanel(
      textOutput("Output")
      
    )
  )
))


server <- function(input, output) {
  
  
  sliderValues <- reactive({
    #This part finds the optimal portfolio using CAPM(which is found in a different script).
    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)]
    toString(max_er_custom)
  })
  
  
  output$Output <- renderText({
    sliderValues()
  
  })
  
  
}

这是仪表板的屏幕截图。前三个值是三种资产的权重,第四个值是该投资组合的预期收益,最后一个值是该投资组合的波动率,均使用历史数据。

标签: rshiny

解决方案


不知道如何在没有文件的情况下复制您的逻辑,但这里有一个示例,其中输入滑块确定sliderValues数据框中的值,这些值又用于创建条形图。

library(shiny); library(ggplot2)
ui <- fluidPage(
    headerPanel(title = "Volatility Slider"),
    sidebarLayout(
        sidebarPanel(
            sliderInput("Risk","Volatility", 0, 0.24, 0.12)
        ),
        mainPanel(
            plotOutput("Output")
        )
    )
)

server <- function(input, output) {
    sliderValues <- reactive({
        data.frame(values = c(input$Risk, 0.7 * (1 - input$Risk), 0.3 * (1-input$Risk)),
                   categories = c("A", "B", "C"))
    })
    
    output$Output <- renderPlot(
        ggplot(sliderValues(), aes(1, values, fill = categories)) +
            geom_col() +
            coord_polar(theta = "y")
    )}

shinyApp(ui = ui, server = server)

在此处输入图像描述


推荐阅读