檢查出這個示例閃亮的應用程序,顯示圖的動態數:https://gist.github.com/wch/5436415/
我適於上述應用用gglotlot繪製汽車數據集。
library(shiny)
library(ggplot2)
library(plotly)
shinyApp(
##### ui #######
ui = fluidPage(
fluidRow(
sliderInput("n",
"Number of plots",
value = 1, min = 1, max = 5)),
fluidRow(
uiOutput("plots"))
),
##### server ######
server = function(input, output) {
data("cars")
# define max number of plots
max_plots <- 5
# generate the plots
output$plots <- renderUI({
plot_output_list <- lapply(1:input$n, function(i) {
plotname <- paste0("plot", i)
plotlyOutput(plotname)
})
# convert the list to a tagList - this is necessary for the list of
# items to display properly
do.call(tagList, plot_output_list)
})
# call renderPlotly for each plot. Plots are only generated when they are
# visible on the web page
for(i in 1:max_plots) {
# Need local so that each item gets its own number. Without it, the value
# of i in the renderPlotly() will be the same across all instances, because
# of when the expression is evaluated
local({
my_i <- i
plotname <- paste0("plot", my_i)
output[[plotname]] <- renderPlotly({
g <- ggplot(cars, aes(x = speed, y = dist)) +
geom_point() +
labs(title = paste0("Plot ", my_i))
g <- ggplotly(g)
dev.off()
g
})
})
}
}
)
創建一個陰謀與許多次要情節:
library(shiny)
library(ggplot2)
library(plotly)
library(grid)
shinyApp(
##### ui #######
ui = fluidPage(
fluidRow(
sliderInput("n",
"Number of plots",
value = 1, min = 1, max = 5)),
fluidRow(
plotlyOutput("plots")
)
),
##### server ######
server = function(input, output) {
data("cars")
# define max number of plots
max_plots <- 5
# generate the plots
output$plots <- renderPlotly({
plot_list <- lapply(1:input$n, function(i) {
g <- ggplot(cars, aes(x = speed, y = dist)) +
geom_point() +
theme(plot.margin = unit(c(3, 1, 1, 1), "lines"))
ggplotly(g)
})
p <- subplot(plot_list[1:input$n], shareX = TRUE, shareY = TRUE) %>%
layout(title = "Car Plots")
dev.off()
p
})
}
)
我應該與ui.r呢? – user3833612
ui包含在上面的代碼中。我添加了評論,使每個部分更清晰。如果你願意的話,你可以把代碼分解成一個ui.R和server.R。 – blondeclover
哦,對不起,我錯過了開始的ui部分。是的,我根據您的示例修改了我的代碼,現在它工作正常。謝謝! – user3833612