2015-12-10 158 views
0

我想繪製一些圖表R使用ggplot packageShinyDashboard。現在我陷入了一個問題。閃亮的ggplot缺失因子水平

enter image description here

在這個例子中我有6個不同的品牌和2個不同的類別。我喜歡做的,所有的品牌將被繪製爲Brand7。這意味着,所有品牌應該有2列:Bike66Buss66。更重要的是,我總是有2個類別,但它的名稱可以更改(可以在可重現示例中使用滑塊)。

可以使用ggplot設置來解決問題,或者應該將一些零值的行添加到data.frame

總而言之,我無法找到合適的解決方案。

下面是可再生的例子。

謝謝!

rm(list = ls()) 
library(shiny) 
library(shinydashboard) 
library(ggplot2) 



# Header ----------------------------------------------------------- 

header <- dashboardHeader(title="Dashboard") 

# Sidebar -------------------------------------------------------------- 

sm <- sidebarMenu(
    menuItem(
    text="Graph1", 
    tabName="Graph1", 
    icon=icon("home") 
) 
) 

sidebar <- dashboardSidebar(sm) 

# Body -------------------------------------------------- 

body <- dashboardBody(

    # Layout -------------------------------------------- 

    tabItems(
    tabItem(
     tabName="Graph1", 

     fluidPage(
     fluidRow(


      box(
      title = "Season", width = 10, status = "info", solidHeader = TRUE, 

      sliderInput("Slider", "Size:", 
         min = 1, max = 99, value = c(66)), 

      plotOutput("Graph1"), 
      plotOutput("Graph2") 

     ) 
     ) 
    ) 
    ) 
) 
) 

# Setup Shiny app UI components ------------------------------------------- 

ui <- dashboardPage(header, sidebar, body, skin="black") 

# Setup Shiny app back-end components ------------------------------------- 

server <- function(input, output) { 

    # Generate data -------------------------------------- 

    df <- reactive ({ 

    set.seed(1992) 
    n=8 

    Category <- sample(c("Bike", "Bus"), n, replace = TRUE, prob = NULL) 
    Category <- paste0(Category, input$Slider) 
    Category <- as.factor(Category) 
    Brand <- sample("Brand", n, replace = TRUE, prob = NULL) 
    Brand <- paste0(Brand, sample(1:14, n, replace = TRUE, prob = NULL)) 
    USD <- abs(rnorm(n))*1000 

    df <- data.frame(Brand, Category, USD) 

    }) 

    # Inputs -------------------------------------- 




    # Plot -------------------------------- 

    output$Graph1 <- renderPlot({ 

    ggplot(df(), aes(x=Brand, y=USD, fill=Category))+ 
     geom_bar(stat='identity', position="dodge") 

回答

2

如果你想做到這一點在目前的形式,你必須添加zero counts

但你也可以用面(注意,我不認爲這有什麼關係Shiny本身)解決它:

的樣本數據

set.seed(1992) 
n=8 

Category <- sample(c("Bike", "Bus"), n, replace = TRUE, prob = NULL) 
Category <- paste0(Category, input$Slider) 
Category <- as.factor(Category) 
Brand <- sample("Brand", n, replace = TRUE, prob = NULL) 
Brand <- paste0(Brand, sample(1:14, n, replace = TRUE, prob = NULL)) 
USD <- abs(rnorm(n))*1000 

df <- data.frame(Brand, Category, USD) 

創建情節

ggplot(df, aes(x=Category, y=USD, fill=Category)) + 
    geom_bar(stat='identity', position="dodge") + facet_grid(~Brand) + 
    theme_classic() 

結果

enter image description here