0

我正在尝试使用来自@blondeclover 的以下代码创建绘图。代码如下 -

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
        })
    }
)

但是,我无法调出我收到的每个子图的标题作为输出。我的情节标题因参数而异。所以,我想将其显示为标题。如何为每个情节呈现标题,而不是为所有人呈现一个标题?

4

1 回答 1

0

我找到了答案。我们需要在 ggplot 代码中使用facet_wrap而不是。ggtitle在这里发布它,这样它对任何偶然发现与我相同的问题的人都会有用。代码如下:

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
        cars$main1 <- "title"
        # generate the plots
        output$plots <- renderPlotly({
            plot_list <- lapply(1:input$n, function(i) {
                g <- ggplot(cars, aes(x = speed, y = dist)) +
                    geom_point() + 
                    facet_wrap(~main1) +
                    theme(plot.margin = unit(c(3, 1, 1, 1), "lines"))
                ggplotly(g)
            })
            p <- subplot(plot_list[1:input$n], shareX = TRUE, shareY = TRUE)
            dev.off()
            p
        })
    }
)

于 2018-03-22T10:28:19.983 回答