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

Var*_*run 6 r shiny plotly

在我的 Shiny 应用程序中,图例trace 0中的图例会产生一个使我的图表不平衡的图例。

这就是图表的样子(注意trace 0图例中的 )。 在此处输入图片说明

然而,trace 0在图例中点击,图表恢复正常

在此处输入图片说明

有没有办法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)))

})
Run Code Online (Sandbox Code Playgroud)

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")))
})
Run Code Online (Sandbox Code Playgroud)

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"))
})
Run Code Online (Sandbox Code Playgroud)

对此的任何帮助将不胜感激。对于无法包含可重现的数据,我提前表示歉意。

amr*_*rrs 5

你的方法有问题。

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

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
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

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"))
})
Run Code Online (Sandbox Code Playgroud)