在Shiny中改变马赛克图的填充

时间:2017-12-30 11:10:57

标签: r shiny

我有以下闪亮的应用程序:

library(shiny)
library(ggplot2)
library(dplyr)
library(networkD3)
library(ggmosaic)

#Loading data
Category <- c("Bankpass", "Bankpass", "Bankpass", "Moving", "Moving")
Subcategory <- c("Stolen", "Lost", "Login", "Address", "New contract")
Weight <- c(10,20,13,40,20)
Duration <- as.character(c(0.2,0.4,0.5,0.44,0.66))
Silence <- as.character(c(0.1,0.3,0.25,0.74,0.26))
df <- data.frame(Category, Subcategory, Weight, Duration, Silence)

ui <- fluidPage(


  tags$div(class="header",
      selectInput("measure", "", c("Duration", "Silence"))
  ),

  mainPanel(
    tags$div(class = "dashboard_main",
             tags$div(class="dashboard_main_left", plotOutput("secondPlot"))

    )
  )

)
server <- function(input, output){

  output$secondPlot <- renderPlot({
    ggplot(data = df) +
      geom_mosaic(aes(weight = Weight, x = product(Category), fill=Duration), 
                  offset = 0, na.rm=TRUE) +  
      theme(axis.text.x=element_text(angle=-25, hjust= .1)) +
      theme(axis.title.x=element_blank()) +
      scale_fill_manual(values=c("#e8f5e9", "#c8e6c9", "#a5d6a7", "#81c784", "#66bb6a"))
  })
}

shinyApp(ui = ui, server= server)

我想现在让第二个情节互动。因此,如果您选择持续时间填充情节&#34; secondPlot&#34;应该是持续时间,如果你选择&#34; Silence&#34;填充应该是&#34;沉默&#34;。

但是,当我将图表的相关代码更改为:

 ggplot(data = df) +
      geom_mosaic(aes(weight = Weight, x = product(Category), fill=input$measure), 
                  offset = 0, na.rm=TRUE) +  
      theme(axis.text.x=element_text(angle=-25, hjust= .1)) +
      theme(axis.title.x=element_blank())

我再也看不到颜色渐变了。对这里出了什么问题的想法?

1 个答案:

答案 0 :(得分:3)

您应该在aes_string内使用geom_mosaic。试试这个:

server <- function(input, output){
  df$prodcat <- product(df$Category)
  output$secondPlot <- renderPlot({
    ggplot(data = df) +
      geom_mosaic(aes_string(weight = "Weight", x = "prodcat", fill=input$measure), 
                  offset = 0, na.rm=TRUE) +  
      theme(axis.text.x=element_text(angle=-25, hjust= .1)) +
      theme(axis.title.x=element_blank()) +
      scale_fill_manual(values=c("#e8f5e9", "#c8e6c9", "#a5d6a7", "#81c784", "#66bb6a"))
  })
}