来自dplyr的plot_ly图在Shiny SelectInput的输入处分解

时间:2018-06-23 15:46:44

标签: r shiny

我正在学习Shiny。

这是无效的代码(以及一些内置的示例数据):

library(tidyverse)
library(shiny)
library(plotly)
library(shinyjs)


analysis_df<- data.frame(
  report_month = c("jan","jan","jan","jan","jan","jan"),
  payee_id = c("59","59","59","59","59","59"),
  Payee = sample(LETTERS[1:5],6,replace = TRUE),
  Attrib_1 = sample(LETTERS[6:10],6,replace = TRUE),
  Attrib_2 = sample(LETTERS[11:15],6,replace = TRUE),
  country_of_sale_iso2 = c("AU","AU","AU","NZ","AU","AU"),
  currency = c("USD","USD","USD","USD","USD","USD"),
  Attrib_3 = c("Pandora-AU","Pandora-AU","Pandora-AU","Pandora-AU","Pandora-AU","Pandora-AU"),
  month_paid = c("jun","jun","jun","jun","jun","jun"),
  Attrib_4 = sample(LETTERS[16:20],6,replace = TRUE),
  Attrib_5 = sample(LETTERS[21:25],6,replace = TRUE),
  units = c("2","8","6","2","10","4"),
  gross = c("0.003254785","0.013019141","0.009764356","0.003254785","0.016273926","0.00650957"),
  reserves_wh = c("0","0","0","0","0","0"),
  rsrv_liq = c("0","0","0","0","0","0"),
  Attrib_7 = c("0.002753548","0.011014193","0.008260645","0.002753548","0.013767741","0.005507097"),
  Attrib_8 = c("3.25E-04","0.001301914","9.76E-04","3.25E-04","0.001627393","6.51E-04"),
  Attrib_9 = c("1.76E-04","7.03E-04","5.27E-04","1.76E-04","8.79E-04","3.52E-04"),
  Attrib_10 = c("0.03","0.03","0.03","0.03","0.03","0.03"),
  Attrib_11 = c("1","1","1","1","1","1"),
  Attrib_12 = c("0.003254785","0.013019141","0.009764356","0.003254785","0.016273926","0.00650957")
)

attribs <- c("Attrib_1","Attrib_2","Attrib_3","Attrib_4")
payees <- analysis_df %>% distinct(Payee) %>% as.vector()

ui <- fluidPage(

  headerPanel("Product Explorer"),

  sidebarPanel(
  selectInput('slice_by', 'Color the Bars By:', choices = attribs, selected = "Attrib_1"),
  sliderInput('plotHeight', 'Adjust Chart Size', 
              min = 100, max = 2000, value = 425)
  ),
  mainPanel(
    plotlyOutput('Plot', height = "900px")
  )
)


server <- function(input, output) {

  output$Plot <- renderPlotly({

    col_cht <- analysis_df %>% 
      filter(payee_id == 59) %>% 
      plot_ly(x = ~report_month, 
              y = ~gross) %>%
      add_bars(color = input$slice_by) %>%
      layout(barmode = "stack",
             height = input$plotHeight)
  })

}

shinyApp(ui, server)

我希望SelectInput可以正常工作,

但是,如果我替换

add_bars(color = input$slice_by) %>%

add_bars(color = ~Attrib_1) %>%

即,对其进行硬编码,该图看起来应该是这样。

1 个答案:

答案 0 :(得分:1)

使用

进行配管时
> analysis_df %>%

analysis_df数据帧传递给函数。因此,在使用〜Attrib_1时,您需要在Attrib_1列中传递值

# > analysis_df$Attrib_1
# [1] H J J H H G

因此,对于analysis_df $ Attrib_1中的级别,该图将获得不同的颜色。

当您使用仅返回一个值(在“选择”中选择的值)的input $ slice_by时。因此,您只能在图中获得一种颜色。

要使其正常工作,请使用

color = analysis_df[, input$slice_by]

如果您不想在管道内使用analysis_df,请在R中搜索非标准评估。使用lazyeval,您可以这样做,

color = interp(~x, x = as.name(input$slice_by))