我想在循环中绘制20个图形,我不想逐个编写输出。所以我正在做一个输出这些图的循环。我在闪亮的画廊中找到了一个很好的例子,展示了如何输出文本。我把它弄好了,但它确实有效。
现在我的问题是:如何将文本输出替换为plotly?我已经准备好了(为了简化我没有在这里展示)。我尝试的是首先用我的情节对象替换strong(paste0(..
行。其次,将renderUI
替换为renderplotly
,并将uiOutput
替换为plotOutput
。我收到错误ggplotly has no applicable method for shiny.tag
我理解plotOutput与标记输出不兼容。那我该怎么办?
server.r:
shinyServer(function(input, output,session) {
lapply(1:2, function(i) {
output[[paste0('b', i)]] <- renderUI({
strong(paste0('Hi, this is output B#', i)) })# to be replaced with a plotly object p
})})
ui.r:
fluidRow(
lapply(1:2, function(i) {
uiOutput(paste0('b', i))
})
)
答案 0 :(得分:2)
查看此示例显示动态数量的图表的闪亮应用:https://gist.github.com/wch/5436415/
我改编了上面的应用程序,用ggplotly绘制汽车数据集。
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
})
}
)