plot在R shiny App中不能正常工作



我试图在按钮被点击后显示一个曲线图,这意味着图表只会在按钮被点击时显示,但图表只是没有显示…有什么线索吗?下面是代码:

shinyApp(
ui = fluidPage(
sidebarLayout(
sidebarPanel(
actionButton("button", "Show Chart")
),
mainPanel(
plotOutput("bar")
)
)
),
server = function(input, output) {
observeEvent(input$button, {
category <- c('task1', 'task2', 'task2','task1','task1')
start_min <- c(0, 0, 16, 45, 40)
stop_min <- c(14.9,18.8,17.5,65.5, 70)
group <- c('A', 'B', 'A', 'A', 'B')
data <- data.frame(category,start_min,stop_min,group)

task_bars <- ggplot(data, mapping=aes(ymin=0, ymax=1,
xmin=start_min, xmax=stop_min,
fill=as.factor(category),
text=paste("Task:", str_wrap(string = category, width = 70,),
"<br>Start: ", format(start_min, digits=1), "min", 
"<br>Stop: ", format(stop_min, digits=1), "min")
)) +
geom_rect(alpha=0.8) +
theme_minimal()+
theme(
axis.title.x=element_text(color="white"), axis.text.x=element_text(color="white"),
axis.text.y=element_blank(), axis.ticks.y=element_blank(),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.border = element_blank(), panel.background = element_blank()) +
scale_fill_discrete(breaks=data$category)

task_bars <- plotly::ggplotly(task_bars, tooltip="text", width = 970, height = 120) %>%
plotly::config(displayModeBar = TRUE) %>% 
plotly::layout(plot_bgcolor='black', paper_bgcolor='black', margin = list(b=30, l=0, r=10, t=30))

print(task_bars)
output$bar <- renderPlotly(task_bars)
})
}
)

您需要将output$bar移到observeEvent之外。我为你的情节创建了一个reactiveValues对象。observeEvent创建绘图,然后在输出中显示。

你也有plotOutput在ui而不是plotlyOutput在ui。

library(shiny)
library(ggplot2)
library(plotly)
task_bars <- reactiveValues(plot = NULL)
shinyApp(
ui = fluidPage(
sidebarLayout(
sidebarPanel(
actionButton("button", "Show Chart")
),
mainPanel(
plotlyOutput("bar")
)
)
),
server = function(input, output) {
observeEvent(input$button, {
category <- c('task1', 'task2', 'task2','task1','task1')
start_min <- c(0, 0, 16, 45, 40)
stop_min <- c(14.9,18.8,17.5,65.5, 70)
group <- c('A', 'B', 'A', 'A', 'B')
data <- data.frame(category,start_min,stop_min,group)

task_bars$plot <- ggplot(data, mapping=aes(ymin=0, ymax=1,
xmin=start_min, xmax=stop_min,
fill=as.factor(category)
)) +
geom_rect(alpha=0.8) +
theme_minimal()+
theme(
axis.title.x=element_text(color="white"), axis.text.x=element_text(color="white"),
axis.text.y=element_blank(), axis.ticks.y=element_blank(),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.border = element_blank(), panel.background = element_blank()) +
scale_fill_discrete(breaks=data$category)
})

output$bar <- renderPlotly({
if(input$button == 0){
return()
} else {
print(plotly::ggplotly(task_bars$plot, tooltip="text", width = 970, height = 120) %>%
plotly::config(displayModeBar = TRUE) %>% 
plotly::layout(plot_bgcolor='black', paper_bgcolor='black', margin = list(b=30, l=0, r=10, t=30))
)
}
})
}
)

最新更新