2017-05-22 30 views
1

考慮以下有光澤應用程式:有條件顏色在Plotly單杆,其中R閃亮

UI

library(shiny) 
library(plotly) 
ui <- fluidPage(
    titlePanel("Random Number Generator"), 
    mainPanel(
     plotlyOutput("random_numbers") 
    ) 
) 

SERVER

server <- function(input, output) { 
    df <- reactive({ 
    runif(100) 
    }) 

    output$random_numbers <- renderPlotly({ 
    plot_ly() %>% 
     add_trace(y = sort(df()), 
       type = 'bar', 
       name = 'Random Numbers', 
       marker = list(color = 'green')) %>% 
     add_trace(y = mean(df()), 
       type = 'bar', 
       name = 'Mean', 
       marker = list(color = 'orange')) 
    }) 
} 

輸出看起來像這樣:

sample graph

問題

有沒有一種方法,我可以顯示在相同的順序其他runif(100)相同的跟蹤平均值,這樣我可以保持升序排列,並保持平均不同的顏色?我希望它看起來像下圖:

what it should look like

回答

1

有一種說法x就可以使用。對於那個你可以傳遞最接近排序數組的索引值。在你的情況下:x = which.min(abs(sort(df()) - mean(df())))

完整的應用程序:

library(shiny) 
library(plotly) 
ui <- fluidPage(
    titlePanel("Random Number Generator"), 
    mainPanel(
    plotlyOutput("random_numbers") 
) 
) 

server <- function(input, output) { 
    df <- reactive({ 
    runif(100) 
    }) 

    output$random_numbers <- renderPlotly({ 
    plot_ly() %>% 
     add_trace(
     x = 1:100, 
     y = sort(df()), 
       type = 'bar', 
       name = 'Random Numbers', 
       marker = list(color = 'green')) %>% 
     add_trace(
     x = which.min(abs(sort(df()) - mean(df()))), 
     y = mean(df()), 
       type = 'bar', 
       name = 'Mean', 
       marker = list(color = 'orange')) 
    }) 
} 


runApp(shinyApp(ui, server), launch.browser = TRUE) 

編輯:更多的代碼密集,但正確的解決方案可以在下面找到。

output$random_numbers <- renderPlotly({ 
    full.seq <- 1:(length(df()) + 1) 
    mean.idx <- which.min(abs(sort(df()) - mean(df()))) 
    if((sort(df()) - mean(df()))[mean.idx] < 0) mean.idx <- mean.idx + 1 
    rand.seq <- full.seq[-mean.idx] 

    plot_ly() %>% 
     add_trace(
     x = rand.seq, 
     y = sort(df()), 
     type = 'bar', 
     name = 'Random Numbers', 
     marker = list(color = 'green')) %>% 
     add_trace(
     x = mean.idx, 
     y = mean(df()), 
     type = 'bar', 
     name = 'Mean', 
     marker = list(color = 'orange')) 
    }) 
+0

打我吧:) –

+0

比賽仍然在,因爲在它的錯誤:d – BigDataScientist

+0

是的,但我有工作要做 - 所以它是你的。不知道你做了陰謀:) –