'r shiny and ggplot2::facet_wrap how can I add categories to facet_wrap without having the original plot resize?
I have a shiny app that lets the user add categories to the facet_wrap. When I start with one category the plot fills the entire box but when I add a second category, the initial plot adjusts to half it size. Is there any way I can set the size, such that the first facet fits half the box and doesn't adjust in size when I add a second category?
Here's what I happens when I choose a second facet category: Current behavior
Here's what I want to happen: desired behavior
Here is a simple reprex--when you add a second feature from select feature
, it adjusts the size of the first plot. I want the first plot to fit half the column, rather than adjusting in size when the second panel is added. Thanks in advance for any suggestions!
library(shiny)
library(tidyverse)
library(glue)
iris_df <- iris %>%
janitor::clean_names() %>%
pivot_longer(sepal_length:petal_width) %>%
mutate(feature = glue("{name}_{species}"))
iris_species <- iris_df %>%
janitor::clean_names() %>%
distinct(species) %>%
pull()
iris_features <- iris_df %>%
janitor::clean_names() %>%
distinct(feature) %>%
pull()
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Reprex"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("species",
"Select species:",
choices = iris_species,
selectize = FALSE,
multiple = TRUE,
selected = iris_species[1]
),
selectInput("features",
"Select feature:",
choices = iris_features,
selectize = TRUE,
multiple = TRUE,
selected = iris_features[1]
),
radioButtons("facets", label = "View all features:",
choices = list("On" = "facet_wrap", "Off" = ""),
selected = "", inline = FALSE)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("densityPlot")
))
)
# Define server logic required to draw a histogram
server <- function(input, output, session) {
observeEvent(input$species,
{updateSelectInput(session,
"features",
choices = unique(iris_df$feature[iris_df$species == input$species]),
selected = iris_df$feature[1])
})
output$densityPlot <- renderPlot({
if (input$facets == '') {
iris_df %>%
filter(species %in% input$species) %>%
filter(feature %in% input$features) %>%
ggplot(aes(value, fill = species)) +
geom_density(alpha = .5) +
theme_light() +
facet_wrap(~name, scales = "free")
}
else {
iris_df %>%
filter(species %in% input$species) %>%
ggplot(aes(value, fill = species)) +
geom_density(alpha = .5) +
theme_light() +
facet_wrap(~name, ncol = 2, scales = "free")
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|