Skip to content

Instantly share code, notes, and snippets.

@RCura
Last active September 16, 2021 14:56
Show Gist options
  • Save RCura/2e92f7659a37c0aad9b95cd210fa517e to your computer and use it in GitHub Desktop.
Save RCura/2e92f7659a37c0aad9b95cd210fa517e to your computer and use it in GitHub Desktop.
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(ggplot2)
library(grid)
library(gridExtra)
## ggplot shared legend
grid_arrange_shared_legend <- function(..., position = c("bottom", "right")) {
plots <- list(...)
position <- match.arg(position)
g <- ggplotGrob(plots[[1]] + theme(legend.position=position))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
lwidth <- sum(legend$width)
gl <- lapply(plots, function(x) x + theme(legend.position="none"))
combined <- switch(position,
"bottom" = arrangeGrob(do.call(arrangeGrob, gl),
legend,
ncol = 1,
heights = unit.c(unit(1, "npc") - lheight, lheight)),
"right" = arrangeGrob(do.call(arrangeGrob, gl),
legend,
ncol = 2,
widths = unit.c(unit(1, "npc") - lwidth, lwidth)))
# combined
grid.draw(combined)
}
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 10,
value = 2)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
p1 <- ggplot(mtcars, aes(cyl, mpg, col = wt)) + geom_point(size = input$bins)
p2 <- ggplot(mtcars, aes(wt, mpg, col = wt)) + geom_point(size = input$bins)
grid_arrange_shared_legend(p1, p2)
})
}
# Run the application
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment