我试图在单击按钮后显示图表,这意味着只有单击按钮时才会显示图表,但图表只是不显示......这有什么线索吗?这是代码:
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
创建绘图,然后它将显示在输出中。
您在 ui 中也有
plotOutput
而不是 ui 中的 plotlyOutput
。
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))
)
}
})
}
)