闪亮的ggplot缺失因子水平

时间:2015-12-10 15:34:57

标签: r ggplot2 shiny shinydashboard

我正在尝试使用R中的ggplot packageShinyDashboard中绘制一些图表。现在我遇到了一个问题。

enter image description here

在这个例子中,我有6个不同的品牌和2个不同的类别。我喜欢做什么,所有品牌都会被绘制成Brand7。这意味着,所有品牌都应该有两列:Bike66Buss66。 更重要的是,我总是有两个类别,但它的名称可以改变(你可以在可重复的例子中使用滑块)。

可以使用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")

1 个答案:

答案 0 :(得分:2)

如果您想在当前表单中执行此操作,则必须添加zero counts

但你也可以用facet来解决它(请注意,我认为这与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