如何在R Shiny中结合checkboxGroupInput与其他输入绘制散点图
Solution: Combine
checkboxGroupInput with Other Inputs in R Shiny for t-SNE Scatter Plots First, let's fix up your incomplete sample data setup so we have a working foundation:
library(dplyr) library(permute) library(Rtsne) library(shiny) library(ggplot2) library(stringr) set.seed(1) meta.df <- data.frame(gene_id=paste0("id",1:10),symbol=paste0("n",rep(permute::shuffle(5),2)),stringsAsFactors=F) clusters.df <- data.frame(cell=paste0("c",1:100),cluster=rep(permute::shuffle(10),10),sample=paste0("s",rep(permute::shuffle(5),20)),stringsAsFactors=F) mat <- matrix(rnorm(10*100),10,100,dimnames=list(meta.df$gene_id,clusters.df$cell)) # Generate complete t-SNE output and merge with metadata tsne.obj <- Rtsne::Rtsne(t(mat), perplexity = 10, seed = 1) tsne.df <- as.data.frame(tsne.obj$Y) %>% rename(TSNE1 = V1, TSNE2 = V2) %>% bind_cols(clusters.df) %>% # Add gene expression values per cell left_join(t(mat) %>% as.data.frame() %>% rownames_to_column("cell"), by = "cell")
Now let's build a Shiny app that seamlessly combines checkboxGroupInput (for selecting genes to visualize) with other interactive inputs to create dynamic t-SNE plots.
Full Working Shiny App Code
ui <- fluidPage( titlePanel("Interactive t-SNE Scatter Plot"), sidebarLayout( sidebarPanel( # Checkbox group for gene selection checkboxGroupInput( inputId = "selected_genes", label = "Select Genes to Visualize", choices = meta.df$gene_id, selected = meta.df$gene_id[1] # Default to first gene ), # Additional input: choose categorical variable to color points by selectInput( inputId = "color_by", label = "Color Points By", choices = c("Cluster" = "cluster", "Sample" = "sample"), selected = "cluster" ), # Optional: pick how to display gene expression radioButtons( inputId = "expr_display", label = "Show Gene Expression As", choices = c("Point Size" = "size", "Point Opacity" = "alpha"), selected = "size" ) ), mainPanel( plotOutput("tsne_plot") ) ) ) server <- function(input, output) { # Reactive data handler: updates based on user inputs reactive_plot_data <- reactive({ req(input$selected_genes) # Wait until genes are selected # Calculate mean expression if multiple genes are chosen if(length(input$selected_genes) > 1) { tsne.df %>% mutate(expression = rowMeans(select(., all_of(input$selected_genes)))) %>% select(TSNE1, TSNE2, all_of(input$color_by), expression) } else { tsne.df %>% select(TSNE1, TSNE2, all_of(input$color_by), expression = all_of(input$selected_genes)) } }) # Render the dynamic t-SNE plot output$tsne_plot <- renderPlot({ plot_data <- reactive_plot_data() color_col <- input$color_by display_type <- input$expr_display # Base plot structure p <- ggplot(plot_data, aes(x = TSNE1, y = TSNE2)) + geom_point(aes(color = .data[[color_col]]), size = 2) + labs( title = "t-SNE Cell Visualization", x = "TSNE1", y = "TSNE2", color = str_to_title(color_col) ) + theme_minimal() # Add gene expression visualization based on user choice if(display_type == "size") { p <- p + geom_point(aes(size = expression), alpha = 0.7) + labs(size = ifelse(length(input$selected_genes) >1, "Mean Expression", "Gene Expression")) } else { p <- p + geom_point(aes(alpha = expression), size = 2) + labs(alpha = ifelse(length(input$selected_genes) >1, "Mean Expression", "Gene Expression")) } p }) } shinyApp(ui = ui, server = server)
Key Details Explained
- Checkbox Group Integration: Users can select one or more genes. If multiple are chosen, the app calculates the mean expression across those genes per cell for cleaner visualization.
- Input Combination: The app pairs gene selection with:
- A dropdown to choose between coloring points by cluster or sample
- Radio buttons to decide if gene expression is shown via point size or opacity
- Reactive Updates: All inputs trigger real-time updates to the plot, thanks to reactive data handling.
- Flexibility: You can easily extend this by adding more inputs (like a slider for point size, or a dropdown for specific gene symbols instead of IDs) based on your needs.
Just make sure you have all required packages installed before running the app!
内容的提问来源于stack exchange,提问作者dan
相关产品推荐
相关产品推荐

