You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R Shiny中使用bslib包设置主题时plot_ly函数失效怎么解决?

问题原因

thematic包的自动主题同步仅支持base R绘图、ggplot2、lattice三类图形输出。你使用ggplotly时是先基于ggplot2生成符合主题的图形,再转成plotly对象,所以能继承主题配置;但直接调用原生plot_ly生成的对象不会自动读取bslib的主题参数,因此适配失效。

修复方案

你可以在生成plot_ly对象时,手动读取当前bslib主题的配色、字体等参数,传给plotly的layout配置实现主题同步,修改后的完整代码如下:

library(shiny)
library(plotly)
library(bslib)
library(ggplot2)
thematic::thematic_shiny(font = "auto")

ui <- fluidPage(
  theme = bs_theme(),
  fluidRow(
    column(6, plotlyOutput(outputId ="p_plotly",width = "100%", height ="100%")  ),
    column(6, plotlyOutput(outputId ="p_ggplotly",width = "100%", height ="100%")  )
  )
)

server <- function(input, output) {
  bs_themer()
  # 实时获取当前主题参数
  current_theme <- reactive({
    bs_get_variables(theme = getCurrentTheme(),
                    c("bg", "fg", "primary", "font-family-base"))
  })
  
  output$p_plotly<-renderPlotly({
    theme_val <- current_theme()
    iris %>% 
      plot_ly(x=~Sepal.Length,y=~Sepal.Width, color = I(theme_val[["primary"]])) %>%
      layout(
        paper_bgcolor = theme_val[["bg"]],
        plot_bgcolor = theme_val[["bg"]],
        font = list(color = theme_val[["fg"]], family = theme_val[["font-family-base"]]),
        xaxis = list(color = theme_val[["fg"]], gridcolor = adjustcolor(theme_val[["fg"]], 0.2)),
        yaxis = list(color = theme_val[["fg"]], gridcolor = adjustcolor(theme_val[["fg"]], 0.2))
      )
  })
  output$p_ggplotly<-renderPlotly({
    plt<-ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+geom_point()
    ggplotly(plt)
  })
}
shinyApp(ui, server)
补充说明
  • 代码中通过getCurrentTheme()实时读取当前生效的bslib主题参数,包括背景色、前景色、主色、字体
  • 把对应的参数手动配置到plotly的画布、坐标轴、字体、网格线等元素上,即可实现和ggplotly一致的主题适配效果
  • 如果需要适配更多主题样式,可以扩展bs_get_variables的参数列表,读取更多主题变量后配置到plotly的对应属性即可

内容的提问来源于stack exchange,提问作者Masoud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:36:01