问题描述
我创建了一个闪亮的应用程序,其中将鼠标悬停在向下钻取图上时,会出现一个条形图,其中显示了特定月份内出售的类别和子类别的数量。我的问题是,例如,即使某类别在5月份内已售出,我还是希望显示一个全月且其计数为零的图。 使用Plotly图表可以做到吗?任何帮助将不胜感激。预先感谢。
library(tidyverse)
library(maps)
library(stringr)
library(shiny)
library(stringr)
library(plotly)
library(dplyr)
library(htmlwidgets)
library(formattable)
library(ggplot2)
library(shinythemes)
library(tidyr)
sales <- read_csv("https://plotly-r.com/data-raw/sales.csv")
sales$order_date<- months(as.Date(sales$order_date))
print(sales)
ui <- fluidPage(
uIoUtput("history"),plotlyOutput("pie",height = 400),uIoUtput('back'),uIoUtput("back1"),uIoUtput("history3"),uIoUtput("history4"),plotlyOutput("pie2",height =400)
)
server <- function(input,output,session) {
drills <- reactiveValues(
category = NULL,sub_category = NULL,id=NULL
)
sales_data <- reactive({
if (!length(drills$category)) {
return(mutate(sales,value = category))
}
sales <- filter(sales,category %in% drills$category)
if (!length(drills$sub_category)){
return(mutate(sales,value = sub_category))
}
sales<- filter(sales,sub_category %in% drills$sub_category)
mutate(sales,value=id)
})
output$pie <- renderPlotly({
d <- count(sales_data(),value)
p <- plot_ly(d,x = ~value,y = ~n,source = "bars1")
if (!length(drills$sub_category)) {
add_pie(p,showlegend=TRUE,labels = ~value,values=~n,customdata=~value,textinfo='label+percent',textposition='inside') %>%
layout(title= drills$category)#showlegend=FALSE,margin=list(b=105,l=100),color=~value)
}else if (!length(drills$id)){
add_pie(p,textposition='inside') %>%
layout(title= drills$category)
}
})
output$history <- renderUI({
if (!length(drills$category))
return(h4("Click the pie chart to drilldown"))
})
observeEvent(event_data("plotly_click",source = "bars1"),{
x <- event_data("plotly_click",source = "bars1")$customdata[[1]]
if (!length(x)) return()
if (!length(drills$category)) {
drills$category <- x
}else{
drills$sub_category<- x
}
})
output$back <- renderUI({
if (!is.null(drills$category) && is.null(drills$sub_category)){
actionButton("clear","Back",icon("chevron-left"))
}
})
output$back1 <- renderUI({
if (!is.null(drills$sub_category)){
actionButton("clear1",icon("chevron-left"))
}
})
observeEvent(input$clear,drills$category<- NULL)
observeEvent(input$clear1,drills$sub_category<- NULL)
f<- reactive({
s <- event_data("plotly_hover",source="bars1")
print(s$customdata)
})
h<- reactive({temp<- sales_data()[sales_data()$value %in% f(),c('sales','order_date')]
temp<- as.data.frame(temp)
tbl<- table(temp$order_date)
tbl<- as.data.frame(tbl)
print(tbl)
})
output$history4<- renderUI({
if (is.null(drills$category) || is.null(drills$sub_category))
return(h2(f()))
})
output$pie2<- renderPlotly({
v<- factor(h()$Var1,levels = month.name)
fig<- plot_ly(h(),x=v,y=h()$Freq,type='bar')
fig <- fig %>% layout(xaxis = list(title = 'Month'),yaxis = list(title = 'Count'),barmode='overlay')
})
}
shinyApp(ui,server)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)