【发布时间】:2015-03-17 21:59:31
【问题描述】:
下面的代码允许用户更改显示的绘图数量。如果用户从滑块中选择 2 输入,则 8 个图出现在一列中。我想在 2 个 2x2 的网格中显示 8 个图。如果用户从滑块输入中选择 3,将有 12 个图显示在 3 个全部为 2x2 的网格中。
因此您可以在下面的代码中看到当前生成了 8 个图并带有标签,并且您会看到这些标签打印在 server.r 文件的以下行中:
print(plot_output_list)
do.call(tagList, plot_output_list)
标签看起来像:
<div id="plot5" class="shiny-plot-output" style="width: 400px ; height: 280px"></div>
生成这些标签后,renderPlot 函数用于在循环中为它们分配一个绘图。这是代码行
output[[plotname]] <- renderPlot({ ......
这会在一列中生成 8 个图,但我想要两个 2x2 网格。
我的问题是:
(1) 我需要设置网格来显示 4 个图,所以我打算使用:par(mfrow=c(2,2)) 但我应该在哪里放置该代码。
(2) 目前生成了8个标签。因为只有 2 个网格,所以应该只生成 2 个标签吗?
(3) 这里应该如何使用renderPlot?目前 RenderPlot 运行 8 次并生成 8 个图,但它应该只运行 2 次循环,因为只有 2 个网格?
不是这个:http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/ 但“网格”包在 R 版本 3.1.2 中不可用
这是您可以使用此代码运行的代码:
install.packages("shiny")
library(rJava
runApp("C://Users/me/folderTOProject")
服务器.r
shinyServer(function(input, output,session) {
max_plots<- reactive({
print("IN reactive function")
NumberOfPlots(input$n)
})
# Insert the right number of plot output objects into the web page
output$plots <- renderUI({
#plot_output_list <- lapply(1:input$n, function(i) {
print("in render UI")
plot_output_list <- lapply(1:max_plots(), function(i) {
plotname <- paste("plot", i, sep="")
plotOutput(plotname, height = 280, width = 400)
})
print(plot_output_list)
# Convert the list to a tagList - this is necessary for the list of items
# to display properly.
do.call(tagList, plot_output_list)
}) #end of output$plots
# Call renderPlot for each one. Plots are only actually generated when they
# are visible on the web page.
observe({
for (i in 1:max_plots()) {
# for (i in seq(1, maxplots(), by=4)) { #use this to only loop twice
# par(mfrow=c(2,2)) #SET UP THE GRID to hold 4 plots..Should this be here?
# Need local so that each item gets its own number. Without it, the value
# of i in the renderPlot() will be the same across all instances, because
# of when the expression is evaluated.
local({
my_i <- i
plotname <- paste("plot", my_i, sep="")
output[[plotname]] <- renderPlot({
data<- as.data.frame(c(1,2,3))
plot(1:my_i, 1:my_i,
xlim = c(1, max_plots()),
ylim = c(1, max_plots()),
main = paste("1:", my_i, ". max plots is ", max_plots(), sep = "")
)
})#end of renderPlot
})#end of local
}#end of loop over max_plots
})
})#end of server
ui.r
shinyUI(pageWithSidebar(
headerPanel("tst"),
sidebarPanel(
sliderInput("n", "Number of plots", value=2, min=1, max=7),
width = 2
),
mainPanel(
# This is the dynamic UI for the plots
uiOutput("plots")
)
))
global.r
NumberOfPlots<-function(n)
{
print("in global")
print(n)
length(seq(from=1 , to=n*4, by = 1))
}
【问题讨论】: