以“闪亮”显示多个绘图(仅显示一个)

时间:2020-03-04 16:44:41

标签: r shiny plotly

我试图在Shiny主面板中并排绘制两个可绘制的饼图,但是仅显示最后一个。但是,可以单独制作两个图而没有问题。

例如,下面是我的代码。 从mtcars数据集开始,我创建了两个额外的列,分别列出了制造商和随机类别(SportSedan)。

mtcars$manuf <- unlist(strsplit(rownames(mtcars), " "))[1]
mtcars$Category <- c(rep("Sport", 22), rep("Sedan", 10))
head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb manuf   Cat
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 Mazda Sport
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 Mazda Sport
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 Mazda Sport
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 Mazda Sport
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 Mazda Sport
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 Mazda Sport

从那里,应用程序用户可以在ligth (mtcars$wt < 3)heavy (mtcars$wt >=3)汽车之间进行选择。

我的app.R

library(shiny)
library(plotly)
library(dplyr)


mtcars$manuf <- unlist(strsplit(rownames(mtcars), " "))[1]
mtcars$Category <- c(rep("Sport", 22), rep("Sedan", 10))


ui <- fluidPage(

    sidebarLayout(
        sidebarPanel(     
            selectInput(
                inputId = "select",
                label = "Select car weigth:",
                choices = c("All","light","heavy")
            ),                
        ),

        mainPanel(
            plotlyOutput("view")
        )
    )
)

server <- function(input, output) {
    dataset <- reactive({
        switch(input$select,
            "All" = mtcars,
            "light" = subset(mtcars, wt < 3),
            "heavy" = subset(mtcars, wt >= 3)
        )
    })

    output$view <- renderPlotly({

        # First plot
        df1 <- dataset() %>% group_by(manuf)
        df1 <- df1 %>% summarize(count=n())
        fig1 <- df1 %>% plot_ly(labels = ~manuf, values = ~count)
        fig1 <- fig1 %>% add_pie(hole = 0.6)
        fig1 <- fig1 %>% layout(title = "Manufacturers",showlegend = F)

        # Second plot
        df2 <- dataset() %>% group_by(Category)
        df2 <- df2 %>% summarize(count=n())
        fig2 <- df2 %>% plot_ly(labels = ~Category, values = ~count)
        fig2 <- fig2 %>% add_pie(hole = 0.6)
        fig2 <- fig2 %>% layout(title = "Categories",showlegend = F)

        # Grouped plots
        subplot(fig1, fig2)
    })
}

shinyApp(ui = ui, server = server)

任何帮助将不胜感激:-)

0 个答案:

没有答案