使用apexcharter制作Shiny小图表时的高度适配问题
解决apexcharter小型图表高度适配与spark_box样式问题
针对你的需求,提供两种可行方案:
方案一:移除spark_box的边框和阴影
spark_box的边框、阴影来自默认CSS样式,通过自定义样式即可覆盖。在UI中添加以下代码,就能移除这些突兀的样式:
tags$style( ".sparkbox { border: none !important; box-shadow: none !important; }" )
修改后的完整App代码:
library(shiny) library(bslib) library(tidyverse) library(apexcharter) myIris <- iris %>% as_tibble() %>% mutate(Species = as.factor(Species)) %>% summarise(Sepal.Length = mean(Sepal.Length), .by = Species) server <- function(input, output, session) { output$spark <- renderSparkBox(spark_box(myIris, type = "column")) session$onSessionEnded(function() {stopApp()}) } ui <- page_fluid( tags$style( ".sparkbox { border: none !important; box-shadow: none !important; }" ), div(class = "content", div(class = "container-xl", card_body("无边框阴影的spark_box (height = 60px)", sparkBoxOutput("spark", height = "60px")) ))) shinyApp(ui, server)
方案二:让apex图表占满可用高度
通过调整apex的多项配置,消除内部留白,让图表完全填充设置的高度:
- 关闭工具栏(避免占用空间)
- 移除坐标轴内边距
- 消除图表偏移量
- 移除网格区域的上下内边距
修改后的renderApexchart代码:
output$chart <- renderApexchart( apex(data = myIris, mapping = aes(x = Species, y = Sepal.Length), type = "column") %>% ax_legend(show = FALSE) %>% ax_dataLabels(enabled = FALSE) %>% ax_yaxis( labels = list(show = FALSE), maxPadding = 0, minPadding = 0 ) %>% ax_xaxis( labels = list(show = FALSE), axisBorder = list(show = FALSE), axisTicks = list(show = FALSE) ) %>% ax_grid( yaxis = list(lines = list(show = FALSE)), xaxis = list(lines = list(show = FALSE)), padding = list(top = 0, bottom = 0) ) %>% ax_chart( toolbar = FALSE, offsetX = 0, offsetY = 0 ) )
完整的对比App代码:
library(shiny) library(bslib) library(tidyverse) library(apexcharter) myIris <- iris %>% as_tibble() %>% mutate(Species = as.factor(Species)) %>% summarise(Sepal.Length = mean(Sepal.Length), .by = Species) server <- function(input, output, session) { output$spark <- renderSparkBox(spark_box(myIris, type = "column")) output$chart <- renderApexchart( apex(data = myIris, mapping = aes(x = Species, y = Sepal.Length), type = "column") %>% ax_legend(show = FALSE) %>% ax_dataLabels(enabled = FALSE) %>% ax_yaxis( labels = list(show = FALSE), maxPadding = 0, minPadding = 0 ) %>% ax_xaxis( labels = list(show = FALSE), axisBorder = list(show = FALSE), axisTicks = list(show = FALSE) ) %>% ax_grid( yaxis = list(lines = list(show = FALSE)), xaxis = list(lines = list(show = FALSE)), padding = list(top = 0, bottom = 0) ) %>% ax_chart( toolbar = FALSE, offsetX = 0, offsetY = 0 ) ) session$onSessionEnded(function() {stopApp()}) } ui <- page_fluid( tags$style( ".sparkbox { border: none !important; box-shadow: none !important; }" ), div(class = "content", div(class = "container-xl", card_body("无边框阴影的spark_box (height = 60px)", sparkBoxOutput("spark", height = "60px")), card_body("占满高度的apex图表 (height = 60px)", apexchartOutput("chart", height = "60px")) ))) shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者EnisKarra
相关产品推荐
相关产品推荐

