我正在尝试在我的 Shiny 应用程序中生成仪表网格,但是我不确定如何调整正在生成的仪表的布局。这是我的应用程序的代表:
# import libraries
library(shiny)
library(flexdashboard)
library(purrr)
library(magrittr)
ui <- fluidPage(
# add first gauge set to ui
fluidRow(
uiOutput("first_gauge")),
# add second gauge set to ui
fluidRow(
uiOutput("second_gauge"))
)
server <- function(input, output){
# create first set of gauges
output$first_gauge <- renderUI({
# create 4 values and dynamically create gauges
1:4 %>%
purrr::map(flexdashboard::gauge, min = 0, max = 10)
})
# create second set of gauges
output$second_gauge <- renderUI({
# create 4 values and dynamically create gauges
5:8 %>%
purrr::map(flexdashboard::gauge, min = 0, max = 10)
})
}
# run shiny app
shinyApp(ui, server)
该应用程序将 8 个仪表格式化为一长列,如下所示:
gauge1
gauge2
gauge3
gauge4
gauge5
gauge6
gauge7
gauge8
但我试图将它们格式化为 2 行,每行 4 行,如下所示:
gauge1 gauge2 gauge3 gauge4
gauge5 gauge6 gauge7 gauge8
我不需要页面是流动的,它可以被修复。当我尝试弄乱 fluidRow
或 fixedRow
中的 column
设置时,仪表似乎没有移动。
我一直在尝试使用 includeCSS
并弄乱这些边距,但我对 CSS 知之甚少,这似乎并没有修改仪表之间的边距: p>
.html-widget.gauge svg {
height: 40%;
margin-top: 10px;
margin-bottom: 10px;
}
最佳答案
用这个
# import libraries
library(shiny)
library(flexdashboard)
library(purrr)
library(magrittr)
ui <- fluidPage(
# add first gauge set to ui
fluidRow(
uiOutput("first_gauge")),
# add second gauge set to ui
fluidRow(
uiOutput("second_gauge")),
tags$style(".gauge.html-widget {display: inline-block;}"),
)
server <- function(input, output){
# create first set of gauges
output$first_gauge <- renderUI({
# create 4 values and dynamically create gauges
tagList(
1:4 %>%
purrr::map(flexdashboard::gauge, min = 0, max = 10),
tags$script("$('.gauge.html-widget').css({height: '100px', width: '22%'})")
)
})
# create second set of gauges
output$second_gauge <- renderUI({
# create 4 values and dynamically create gauges
tagList(
5:8 %>%
purrr::map(flexdashboard::gauge, min = 0, max = 10),
tags$script("$('.gauge.html-widget').css({height: '100px', width: '22%'})")
)
})
}
# run shiny app
shinyApp(ui, server)
- 我们首先需要将仪表显示从
block
(默认)更改为inline-block
,以便它们可以显示在同一行中。block
表示当前元素占据了当前行的所有宽度,因此我们需要更改它。要改变这一点,我们只需添加一个style
标签即可。 - 默认
flexdashboard::gauge
需要大量的高度和宽度,但是 R 函数没有为我们提供任何参数来更改默认高度和宽度,并且它使用style= “xxx”
为HTML之后的CSS,具有最高优先级。添加style
标签不会完成这项工作。我们需要使用 javascript 来改变这个。由于仪表是从服务器动态渲染的,因此还需要在服务器上添加脚本。 - 每行显示 4 个仪表,每个仪表占用宽度的 25%,但原始样式中添加了一些填充,因此我们不能使用精确的 25,必须小于这个数字。这里使用的是22,将其更改为您想要的合理数字。
关于css - 在 R Shiny 应用程序中调整flexdashboard仪表的布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71843406/