首页 > 解决方案 > R markdown 与每个情节的旋转画廊式幻灯片?

问题描述

所以例如假设我有这三个图

p1 <- iris%>%ggplot(aes(x=Sepal.Length,y=Sepal.Width))+geom_point()
p2 <- iris%>%ggplot(aes(x=Sepal.Length,y=Sepal.Width))+geom_bar(stat="identity",  width = 1, fill="#98ff98")
p3 <- iris%>%ggplot(aes(x=Species,y=Sepal.Width))+geom_bar(stat="identity",  width = 1, fill="blue")

因此,而不是在 html markdown 中单独打印每个图,以便用户必须向下滚动才能查看每个图,有没有办法输出某种 ui,其中左侧是绘图,右侧是地块的选择。然后用户可以简单地选择要查看的绘图,它将出现在左侧。这可能吗?我问的原因是因为每次比较我通常可以有 10-20 个数字,这会很快变得笨拙,我认为这将是组织它们的好方法。

谢谢!

标签: rr-markdown

解决方案


也许这样的事情可以让你开始

library(shiny)

# create a list of plots
plots <- list(
  p1 = iris%>%ggplot(aes(x=Sepal.Length,y=Sepal.Width))+geom_point(),
  p2 = iris%>%ggplot(aes(x=Sepal.Length,y=Sepal.Width))+geom_bar(stat="identity",  width = 1, fill="#98ff98"),
  p3 = iris%>%ggplot(aes(x=Species,y=Sepal.Width))+geom_bar(stat="identity",  width = 1, fill="blue")
)


# put names of plots in a list in sidebar
ui <- fluidPage(sidebarLayout(
  sidebarPanel(tags$ul(purrr::map(names(plots), ~tags$li(actionLink(paste0("show", .), .))))),
  mainPanel(plotOutput("currentplot"))
))

server <- function(input, output, session) {
  # draw the first plot by default
  current_plot <- reactiveVal(plots[[1]]);
  
  # set up observers for each of the action links in the UI
  purrr::map(names(plots), function(p) {
    observeEvent(input[[paste0("show",p)]], {
      # set current plot
      current_plot(plots[[p]])
    })
  })
  
  # render whatever the current plot is
  output$currentplot <- renderPlot(current_plot())
    
}

shinyApp(ui, server)

这将为您提供左侧的绘图列表,并将绘制您在右侧单击的任何绘图。

如果您想编写一些 javascript,您可能可以提高效率,但这至少给出了它如何工作的基本概念。


推荐阅读