我想制作Shiny app
,它会使用ggvis
包在我选择的参数上绘制cumstom图。
如果我选择所有品牌,我想得到这个情节:
但是当我只选择一个特定品牌时,情节应如下所示:
我尝试了不同的方法,但没有一个能给我预期的结果。
请问,请提出如何解决这个问题的想法?
此外,我还包括可重复的示例:
library(shiny)
library(shinydashboard)
library(plyr)
library(ggvis)
# Header -----------------------------------------------------------
header <- dashboardHeader(title= "DashBoard")
# Sidebar --------------------------------------------------------------
sm <- sidebarMenu(
menuItem(
text="GGVIS",
tabName="GGVIS",
icon=icon("eye")
)
)
sidebar <- dashboardSidebar(sm)
# Body --------------------------------------------------
body <- dashboardBody(
# Layout --------------------------------------------
tabItems(
tabItem(
tabName="GGVIS",
fluidPage(
fluidRow(
title = "Inputs", status = "warning", width = 2, solidHeader = TRUE, collapsible = TRUE,
uiOutput("Category"),
uiOutput("Brand"),
uiOutput("Values"),
ggvisOutput("p")
)
)
)
)
)
# Setup Shiny app UI components -------------------------------------------
ui <- dashboardPage(header, sidebar, body)
# Setup Shiny app back-end components -------------------------------------
server <- function(input, output) {
set.seed(1992)
n=101
Letter <- sample(c("a", "b", "c"), n, replace = TRUE, prob = NULL)
Category <- sample(c("Car", "Bus", "Bike"), n, replace = TRUE, prob = NULL)
Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
Brand <- paste0(Brand, sample(1:14, n, replace = TRUE, prob = NULL))
USD <- abs(rnorm(n))*100
df <- data.frame(Letter, Category, Brand, USD)
# Inputs --------------------------------------
output$Category <- renderUI({
selectInput("Category", "Choose category:",
choices = c("Car","Bus", "Bike" ))
})
output$Brand <- renderUI({
df2 <- df[df$Category %in% input$Category,]
selectInput("Brand",
"Brand:",
c("All", unique(as.character(df2$Brand))))
})
# -----------------------------------------------------------------------------
data2 <- reactive({
df <- df[df$Category %in% input$Category,]
df <- df[df$Brand %in% input$Brand,] # if I comment this line, I get All brands graph
df <- droplevels(df)
df <- ddply(df, c("Letter", "Category", "Brand"), summarise, "USD" = sum(USD))
})
data2%>% group_by(Brand) %>%
ggvis(x = ~factor(Letter, levels = c("a", "b", "c")), y = ~USD, fill = ~Brand, fillOpacity := 1) %>%
layer_bars() %>%
add_axis("x", title = "Letter") %>% bind_shiny("p")
# -----------------------------------------------------------------------------
}
# Render Shiny app --------------------------------------------------------
shinyApp(ui, server)
答案 0 :(得分:2)
尝试
1)不要将df改为反应性
data2 <- reactive({
df3=df
df3 <- df3[df3$Category %in% input$Category,]
df3 <- df3[df3$Brand %in% input$Brand,] # if I comment this line, I get All brands graph
df3 <- droplevels(df3)
df3<- ddply(df3, c("Letter", "Category", "Brand"), summarise, "USD" = sum(USD))
})
2)添加if语句
if(!"All" %in% input$Brand){
df3 <- df3[df3$Brand %in% input$Brand,] # if I comment this line, I get All brands graph
}