R/shinyjs : Plot appears beyond the box width after using function show/hide sidebar

标签 r ggplot2 shiny shinydashboard shinyjs

几天以来,我试图找到解决方案,以在使用功能显示/隐藏侧边栏时在 Shiny 的应用程序中错误地显示(超出框宽度)。

这是示例代码:

library(shiny)
library(shinydashboard)
library(ggplot2)
library(shinyjs)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    useShinyjs(),
    extendShinyjs(text = 'shinyjs.hideSidebar = function(params) { $("body").addClass("sidebar-collapse") }'),
    extendShinyjs(text='shinyjs.showSidebar = function(params) { $("body").removeClass("sidebar-collapse") }'),
    fluidRow(tabsetPanel(id='tabs',
                         tabPanel(value=1,title="Plot1",
                                  fluidRow(
                                    column(12,
                                  plotOutput('plot1', height=800)))),
                         tabPanel(value=2, title="Plot2",
                                  fluidRow(
                                    column(12,
                                  plotOutput('plot2', height=800))))
             )
      )))
  )
)

server <- function(input, output, session) { 
  output$plot1 <- renderPlot({
    out <- ggplot(data.frame(X1=rnorm(1000)),aes(X1))+
      geom_density(fill='light blue')+
      theme_minimal()
    print(out)
  })
  output$plot2 <- renderPlot({
    out <- ggplot(data.frame(X1=rnorm(1000)),aes(X1))+
      geom_density(fill='light blue')+
      theme_minimal()
    print(out)
  })

  observe({
    if (input$tabs == 1) {
      js$hideSidebar()
    }
    else {
      js$showSidebar()
    }
  })
}

shinyApp(ui, server)

正如我们在此示例代码中所见,我希望在用户打开第二个选项卡时出现侧边栏(侧边栏在 input$tabs == 1 时折叠)。它工作得很好,除非我按下查看 tab2,然后返回到 tab1 并再次到 tab2 ,调整绘图大小并切割 x 轴:

enter image description here

最佳答案

一种“hacky”方法是在添加/删除侧边栏时触发窗口调整大小事件,以在显示/隐藏侧边栏后强制以正确的大小重新绘制绘图:

extendShinyjs(text = 'shinyjs.hideSidebar = function(params) { $("body").addClass("sidebar-collapse"); 
              $(window).trigger("resize"); }'),
extendShinyjs(text='shinyjs.showSidebar = function(params) { $("body").removeClass("sidebar-collapse"); 
              $(window).trigger("resize"); }')

关于R/shinyjs : Plot appears beyond the box width after using function show/hide sidebar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41824052/

相关文章:

r - 将输入保存在文件中以在另一个 session 中继续 R Shiny App 中的数据分析

重置数据表中的行选择并在 Shiny 中删除包含该表的选项卡

mysql - 使用 MySQL 查询将二分图数据转换为单模式?

r - 如何在R中获取对象的容器类型?

r - plotly 否决 ggplot 2's scale_fill_manual' s 标签

r - 如何在 R ggplot2 中更改 geom_tile 的调色板

r - 当缺少结果时,使用 nlme 正确建模纵向相关性 (R)

r - 如何在 R 中为所有 plot.default、plot 或 lines 调用默认设置颜色

r - 将数字(小时)转换为时间 (HH :MM) in x-axis in ggplot

使用 AWS Cognito 进行 R Shiny 身份验证