考虑以下闪亮的应用:
UI
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(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'))
})
}
输出如下:
问题
有没有办法可以在同一条迹线上以与其他runif(100)相同的顺序显示均值,这样我可以保持升序并保持平均值不同?我希望它看起来像下图:
答案 0 :(得分: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'))
})