如何解决R Shiny中shinyalert/showtext导致图表文本尺寸变化问题?
问题描述
- 开发R Shiny应用时,需要用户输入指定范围内的高精度数值:仅用
sliderInput无法满足精度需求;设置输入框min/max限制会改变数值显示格式,且无法修正非法输入,因此使用shinyalert弹出模态框提示用户。 - 启用
showtext包使用目标字体时,切换屏幕尺寸或执行更新操作会导致图表文本尺寸异常变化、排版混乱;移除showtext包后问题消失,但无法使用目标字体。
解决方案
方法1:临时启用showtext并固定绘图DPI
避免全局启用showtext_auto(),仅在绘图时临时激活showtext,同时明确指定绘图的DPI与showtext配置一致,防止尺寸缩放异常:
步骤1:配置showtext(不要启用自动渲染)
library(shiny) library(tidyverse) library(bslib) library(showtext) font_add_google(name = "Jost") showtext_opts(dpi = 96) # 不要调用showtext_auto()
步骤2:修改renderPlot逻辑
server <- function(input, output) { theme_set(theme_minimal(base_size = 20)) output$distPlot <- renderPlot({ # 绘图前临时启用showtext showtext_begin() x <- tibble(x = faithful[, 2]) p <- ggplot(x) + geom_histogram(aes(x = x), bins = input$bins) + labs(title = "My title and other text gets jumbled up", subtitle = glue::glue("{input$bins} bins")) # 绘图完成后关闭showtext showtext_end() return(p) }, dpi = 96) # 固定DPI与showtext配置匹配 }
方法2:用系统字体替代showtext
利用bslib已加载的Google字体,让ggplot直接调用系统中的该字体,完全避开showtext的冲突:
步骤1:确保字体安装到系统
# 安装字体到系统(仅需运行一次) sysfonts::font_add_google("Jost", "Jost") sysfonts::font_families() # 确认"Jost"已在列表中
步骤2:ggplot直接指定字体族
server <- function(input, output) { # 主题中直接使用系统字体 theme_set(theme_minimal(base_size = 20, base_family = "Jost")) output$distPlot <- renderPlot({ x <- tibble(x = faithful[, 2]) ggplot(x) + geom_histogram(aes(x = x), bins = input$bins) + labs(title = "My title and other text gets jumbled up", subtitle = glue::glue("{input$bins} bins")) }) }
此方法无需加载showtext,UI和绘图字体统一由bslib和系统字体管理,不会出现尺寸异常。
方法3:锁定绘图容器尺寸
在plotOutput中明确固定高度(宽度可保留自适应),避免屏幕尺寸变化时触发的重新渲染导致字体缩放:
plotOutput("distPlot", width = "100%", height = "400px")
内容的提问来源于stack exchange,提问作者Jamie
相关产品推荐
相关产品推荐

