为每个子图提供标题-R Shiny [英] Provide title to each of the subplots - R Shiny

查看:57
本文介绍了为每个子图提供标题-R Shiny的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用@blondeclover中的以下代码创建图.代码如下-

I am trying to create plots using the following code from @blondeclover. The code is as follows -

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

但是,我无法显示我作为输出收到的每个子图的标题.我的情节的标题通过参数变化.因此,我想将其显示为标题.如何呈现每个图的标题,而不是全部显示一个标题?

However, I am unable to bring up the title of each subplots I receive as output. My plot's title varies via a parameter. So, I want to display it as title. How to render title for each plot instead of a single title for all?

推荐答案

我找到了答案.我们需要在ggplot代码中使用 facet_wrap 而不是 ggtitle .将其发布在此处,这样对于与我的问题相同的任何人都将非常有用.代码如下:

I found the answer. We need to use facet_wrap instead of ggtitle in the ggplot code. Posting it here, so that it would be useful for anyone who stumble on the same issue as mine. Code is as follows:

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

这篇关于为每个子图提供标题-R Shiny的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆