R Plotly无法从条形图中删除跟踪0

时间:2017-10-06 12:44:32

标签: r shiny plotly

在我的Shiny应用程序中,在图例中产生trace 0,使我的图形失衡。

这就是图表的样子(注意图例中的trace 0)。 enter image description here

但是,点击图例中的trace 0,图表会恢复正常

enter image description here

有没有办法从我的情节中完全删除这个trace 0

这是我的代码:

1)我的数据框首先在reactive函数内过滤

global_evolution=reactive({

  results_combined %>%
  filter(!is.na(SVM_LABEL_QOL) & SVM_LABEL_QOL=='QoL' & globalsegment==input$inp_pg1segment & Account==input$inp_pg1clientsfiltered & Date >=input$inp_pg1daterange[1] & Date <=input$inp_pg1daterange[2]) %>% #Input: Account
  select(Account,Date,SVM_LABEL_DIMENSION) %>%
  mutate(Month=month(as.Date(format(as.POSIXct(Date),format = "%d/%m/%Y"),"%d/%m/%Y"))) %>%
  select(Account,Month,SVM_LABEL_DIMENSION,-Date) %>%
  group_by(Month,SVM_LABEL_DIMENSION) %>%
  summarise(Monthly_Count=n()) %>%
  spread(SVM_LABEL_DIMENSION,Monthly_Count) %>%
  ungroup() %>%
  mutate(Month=month.abb[Month]) %>%
  mutate_all(funs(replace(., is.na(.), 0)))

})

2)然后对另一个reactive函数内的已过滤数据框进行了一些更改

global_evolution_final=reactive({
global_evolution() %>%
  mutate(Month=factor(Month,levels=c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")))
})

3)最后,我使用plot_ly构建条形图。但是无法移除trace 0

output$pg1evolution <- renderPlotly({

colNames <- names(global_evolution_final())[-1] #Assuming Month is the first column

p <- plotly::plot_ly(data = global_evolution_final(), x = ~Month, type = "bar")

for(trace in colNames){
  p <- p %>% plotly::add_trace(y = as.formula(paste0("~`", trace, "`")), name = trace)
}

p %>% 
  layout(title = "Trend Over Time",showlegend = FALSE,
         xaxis = list(title = ""),
         yaxis = list (title = "Monthly Count of QoL Tweets"))
})

对此的任何帮助将不胜感激。 我提前道歉,因为无法包含可重复的数据。

1 个答案:

答案 0 :(得分:2)

您的方法存在问题。

请检查以下可重现的代码以修复您的问题。

df <- iris

p <- plotly::plot_ly()

colNames <- names(df)

colNames <- colNames[-which(colNames == 'Species')]


for(trace in colNames){
  p <- p %>% plotly::add_trace(data= df, x = ~ Species, y = as.formula(paste0("~`", trace, "`")), name = trace)

  print(paste0("~`", trace, "`"))

}

p

enter image description here

理想情况下,您修改的代码应该是这样的:

output$pg1evolution <- renderPlotly({

colNames <- names(global_evolution_final())[-1] #Assuming Month is the first column

p <- plotly::plot_ly()

for(trace in colNames){
  p <- p %>% plotly::add_trace(data = global_evolution_final(), x = ~Month, y = as.formula(paste0("~`", trace, "`")), name = trace, type = "bar")
}

p %>% 
  layout(title = "Trend Over Time",showlegend = FALSE,
         xaxis = list(title = ""),
         yaxis = list (title = "Monthly Count of QoL Tweets"))
})