'Display multiple plotly plots in Shiny (only one appears)
I am trying to plot two plotly pie charts side by side in the Shiny main panel, but only the last one shows up. However, the two plots could be produced without problem individually.
As an example, my code below.
Starting from the mtcars dataset, I created two extra columns listing the manufacturer and random categories (Sport and Sedan).
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
From there, the app user can choose between ligth (mtcars$wt < 3) and heavy (mtcars$wt >=3) cars.
My 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)
Any help would be greatly appreciated :-)
Solution 1:[1]
Include this and give it a try:
fig<-subplot(fig1,fig2)
fig
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arjun |
